Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Multiple Arrays And Foreach To Put Into A Mysql Db?


I created 3 arrays with data and i want to insert them i a mysql db. PHP Code:




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Accessing Multiple Arrays Using Foreach
I have been searching all afternoon for an answer to this and haven´t found a solution so my last resort is asking here I am collecting links from a few documents on our site using this:

<?php 
  $data = file_get_contents('http://www.example.com/');
  
   preg_match_all("/out.php?url=(.+?)" target/",$data,$match);
   preg_match_all("/class="id" title="(.+?)"/",$data,$desc);
   
  foreach($match[1] as $url ) && foreach($desc[1] as $fulldesc){
     
         echo urldecode($url);
         echo "| $fulldesc<br>";
        
          }?>

Basically , I want to output all the links and their respective descriptions separated by a pipe character.

But reading from the two arrays is giving me a bit of a hard time.I now know I cannot use the && operator, I just left it in so you guys could see what I´m trying to do. How can I do this?

I´m not much of a programmer but from what I have read the other option I have is using multi-dimensional arrays? I might be extracting the URL, the description and then some more data later on so this might be a better approach.

Insert Multiple Arrays Into Mysql
I am having problems writing the code to generate my SQL INSERT query. I have 3 arrays and one static variable ($cat_number):

$track_name[]
$music_link[]
$track_number[]
$cat_number

Should I be using a foreach command. I know how to insert multiple values but its generating the query that i'm not sure about.

INSERT INTO table (track_name, music_link, cat_number, track_number)
VALUES
(var1,var2,var3,var4),
(var5,var6,var7,var8),
(var9,var10,var11,var12);

I don't want to store the actual array in the dataabase, I am just using an array to catch the data.

Multiple Selections, Arrays, And MySQL
OK this place has been great with explaining things that are way over my head, now I could use a boost to get my brain working again. I have a form with a drop down menu with multiple selections. When the form is submitted it shows up in the DB field as "array", as well as the page where I how the form's info. I think I have to set up an array, and loop(?) it, or do I need to implode the array? And how and where would I put these commands on this incredible messy form page. Would someone mind helping me get started?

Here's the form: (please don't make fun of me, I used to a Dreamweaver extension to create the form using PHP, before I decided to try and write this stuff myself. I am re-doing the form but this actually works for now, so I am using it. Code:

Arrays And Foreach
I have a multi-dimensionsal array in the form of a 6 x 10 table. I have 2 problems:

1) The foreach statement that inputs each row into a table, and

2) The php syntax in the table.

First, I'm still building, so the input is in the form of a string that I 'extract' data from. There are 7 input strings in the following form: Code:


Foreach With Multidimensional Arrays
Can foreach() be used to loop through a multidimensional array?

Looping Through Arrays With Foreach
Foreach is a language construct, meant for looping through arrays.
There are two syntaxes; the second is a minor but useful extension
of the first:

foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

For example:
<?php
$arr = array("one", "two", "three");
foreach ($arr as $value) {
echo "Value: $value
";
}
?>

This will output:
Value: one
Value: two
Value: three

--=[ Why not to use list & each ]=--

Another method to loop through an array is the following:
<?php
while (list(, $value) = each($arr)) {
echo "Value: $value<br />
";
}
?>

This has some disadvantages:

- It is less clear, because list() looks like a function but
actually works the other way around: instead of returning
something, it takes a parameter by being the left-hand side
of the expression and assigns values to the parameters.
- You have to reset() the array if you want to loop through it
again.
- It is approx. three times slower than foreach.

--=[ About for & count ]=--

Another method to loop through an array:
for ($i = 0; $i < count($arr); $i++) {
echo "value: $arr[$i]
";
}

Consider this array:
array(5 => "Five");

The above for-loop would loop from elements 0 through 5, while
only one element exists. If this is what you want, the for-loop
is an effective way to loop through an array. If not, use
foreach instead.

Printing Arrays In A ForEach Statement?
I have the the following script which simply parses a remote file and sets the item I am looking for into an array. My question is how do I turn that array into an echo or print statement. PHP Code:

Foreach Loop Contains Arrays In Some Values
I'm looping through the keys and values of a form submission using

foreach($_POST as $key => $value)
echo "$key = $value<br>";

No problems there. All works as expected. But seveal of the values are
arrays and the echo comes out like:

subjectone = Array
subjecttwo = Array

There could be as many as 9 elements in each array but there may be as
few as one. How can I get those $value that are arrays to echo the
entire array using a foreach loop? I would like to end up with all
values printed in the page whether in an array or not.

Foreach Loop With Nested Arrays
I haven't programmed in PHP in quite a while. Could anyone help me
with a foreach loop in a nested array? I have a function which returns
$stock (for an online pricing catalog).

$stock[0] is ( [0] =Item, [1] =Sale, ...) an array of column
headers.
$stock[1][$i] is ([Item] =SL, [Sale] =300, ...) an array of
column headers to value for item $i

What I have to print the header row for the pricing table is:
print("<TR>");
foreach ($stock[0] as $num =$val) {
print("<TH>" + $val + "</TH>");
}
print("</TR>");

I've also tried ($stock[0] as $x) print($x).

What returns is five zeroes. Not in table cells, just "<TR>00000</
TR>".

Does anyone have any ideas what I've done?

Multiple Items In Foreach()
Can someone tell me what im doing wrong with the code bellow please? I get print_ticket called lots of times, with 1 as the hash,name,ticket_no responce.

(i have chequed that the query is returning the right results).

$return = pg_query($pg_connection, $query);
        $data   = pg_fetch_array($return);                   

foreach ( $data as $temp ) {
   
echo print_ticket ($temp['hash'],$temp['name'],$temp['ticket_no']);   
}

Deleting Multiple Checked Rows With Foreach()
I'm trying to delete multiple entries from a mysql table using the following script:
variables are passed using: PHP Code:

How To Sort Multiple Arrays?
I have two arrays, $arr1 and $arr2.

Values in the first corresponds to the same index-values in the second.

How do I sort these array's ascending according to $arr1?

Echoing Multiple Arrays
I have a products table that I want to echo the results of 3 different categories, I can query the db just fine and get results for a single category, but I'm a newb to PHP and don't know the trick way to do slick recursion. Code:

MySQL Array/foreach
I have table with about 20 fields in it.  I want to be able to dynamically pull the data for a certain record and create an array with the keys as the fields names and of course the data as the value.

Here's what I have so far (and it's not working    ):

function get_data($record_id)
  {
  $query = mysql_query("SELECT * FROM table where record_id = '$record_id'")
  or die(mysql_error()); 
  while($row = mysql_fetch_array($query )) {
  foreach ($row as $key => $value) {
  $data .= "&$key=$value";
  }
  } 
  return $data;
  }
Now I want to be able to call the function and work with the data I'm trying to call.

$record_id = 'xxxxxxxxx';
$test = get_data($record_id);
$name = $test['username']; //This would be the username field from the table
echo $name;

All I get is a blank screen when I run this and I know the problem is in the foreach statement I tried to write.

Result From Mysql Into Foreach?
when using mysql_fetch_array($result)

I usually toss that into a while loop like so

while($row = mysql_fetch_array($result)){
...
}
however I was wondering if there was a way to put it in a foreach statement like so

foreach(mysql_fetch_array($result) as $row){
...
}
Is that legit? Will this work?

Multiple Queries Or Sorting Arrays?
I have two tables, one with info about users, and one with gamestatistics. On one page I do four queries to these two tables and present it in four separate tables (ie table one - names and scored goals, sorted by goals desc; table two - names and played games, sorted by games desc ...).

I would like to run one query instead and fetch all the data needed, and then sort the array four times in different orders. Can this be done, and if so, how? What's the most efficient way to do this, multiple queries or sorting an array?

Inserting Elements Of Multiple Arrays In Database
I am stuck when trying to pass the contents of multiple arrays to an INSERT statement. Here is my code:

Selecting Multiple Arrays And Putting Them Into One Variable
Is there a way of assigning lets say $argv[3] through to $argv[10] to one variable??
Also is it possible to assign all of an array after a certain number to a variable??
The reason i wish to do this: I am using a forwarder pointing to a php script.

This script uses exim variables to then send on the email to another couple of addresses.
When a user puts a " in the message body it splits the body into multiple arrays instead of just the one.

Using PHP Funtions With Multiple Arrays --Parse Errors
I am in the proccess of converting/updating the origonal existing webpage, www.BradleyBrokers.com/clients/htm, with php to do several new php functions
and could use a little help. Here is the script I am having trouble writing. i.e. parsing errors: Code:

Multiple Array Selection From Database Instead Of In-Page Arrays
Have posted before, but will simplify problem here. For original post go to
http://forums.devshed.com/t80025/s.html

I have setup 2 arrays like so in my one page script:

Code: ( php )

Arrays In MySQL
Can I store an array into an SQL database and then take it back out and it would still be an array?

Arrays Into Mysql
The mysterious message: Couldn't add data to the CATLINK table:Unknown column 'Manufacturing' in 'field list' PHP Code:

MySQL Query And Arrays
I have a 'links' category on Table A and I want to retrieve the links from the Table and display them in a list-like fashion when the page is called upon. How would I go about seperating the links from one another (there a space inbetween each link.. EXAMPLE: http://asdf.com http://asdasd.com http://asdfff.com), loading them into an array (or using the best possible method to acces them easily) and then displaying them in a list like fashion..?

Arrays And MySQL Querys
I can't get an $array[key] to be used as a select query on a mySQL database.

I have a 'parts list' which displays on a page (works fine) and is a form.
At the end of each row is a input type='text' (quantity) cell with a default
0

The quantity can be altered.
At the bottom of the table (form) is a submit to basket Button

echo "<form action='basket.php' method='POST'>....

Arrays And While Mysql Functions
How can I get this array to work? I am trying to add data to an array for every row of data? This is a sellection of queries that I need to parse into an array so a function can use the arra to draw a graph. I am new to arrays how can I get this to work? Code:

Arrays Working With MySQL
How can I grab a certain field of a Multi-Dimensional Array using the ID. I have set for that Array? I just want to be able to create a simple function to do pretty much what this function does, but for an array. Code:

Passing PHP Arrays To Mysql Best Solution
I am relatively new to PHP and until now I have only needed to use relatively simple php/mysql solutions.

I am working on a problem where I need to store CD information (Artist Name, Album Name, Track Names, Catalog Number)

I am working on a solution with two tables "album" and "tracks" and I am using the catalog number as a key to link the two.

The problem I am having is coming up with the best way to populate the tracks table as there are several tracks for each release. I am assuming that an array would be the correct way and maybe a dynamic form to input the tracks where you decide the number you need to add and this then creates a form with "n" input boxes?

Sorting Arrays Retrieved From A MySQL Db
I am trying to make a news system. I have done it, but the news are listed with the last on at the bottom. This makes it kind of troublesome to read the latest news when you enter the site and there are a lot of news items, cause you would have to scroll down.
PHP Code:

MySQL Field Type For Arrays
What type of field type are arrays stuffed into? VARCHAR ? TEXT?

Populating Arrays From MySQL Query
I have the following code: http://pastebin.com/746601

The field 'material' in 'is_material' contains multiple values for each
record in 'is_details'. Because of this I have used
'is_material_lookup' as a reference lookup table containing the
'style_code' and 'material_code' which refer to their full details in
the respective tables.

Currently I have got the script outputting all the details and one
material then in the next block of data, repeating the details with a
different material. What I would like to achieve is having 1 block of
data with a list of all materials in that, instead of the repeat, but
sadly I can't know exactly how to do it.

How To Insert Arrays Into Mysql Database
This is my order.php file. Now I try to make a new php-file for processing the ordered items on this page, into another table "ordered_products" in the database. I want to INPUT following values into the table "ordered_products":
'order_num', 'order_item' and 'order_ant'

I know how to insert rows in a table using the INSERT query, but I don't know how to do it while looping the arrays. I have to fetch the arrays from this page, and insert them row by row in the "ordered_products" table. Code:

Using Arrays With Mysql Query Results
im currently in the process of making a piece of code that will firstly take all the data from a table in mysql and then assign it to an array. This data will consist of several different rows of data each with different infomation for each field in the table.

i want to be able to use an array in a loop so that depending on which number of the loop is on will change the infomation that is assigned to a certain array. Code:

Merging 2 Mysql Resultant Arrays
im currently executing sql queries on two seperate mysql servers.  i take back each of these results into individual tables to display them. 

What i wanted to do was perform a merge of the two arrays, so that i could order the results by my "TimeStamp" field.

When i try to perform a basic " $mergedresult = array_merge($result, $isaresult); " i get the following.

"
Warning: array_merge() [function.array-merge]: Argument #1 is not an array in C:Program Filesxampplitehtdocsseatpub.php on line 164

Warning: array_merge() [function.array-merge]: Argument #2 is not an array in C:Program Filesxampplitehtdocsseatpub.php on line 164   "

Im rather new to this and so havent delt with arrays before, but im under the impression my results from the sql queries, are Assoc arrays.  can these be merged ? do i need to use an alternate php function ?

Pesky Checkbox Arrays And A MySQL Song Database
I'm not one who likes to ask for help, so for the last three days my brain has been turning to mush while I try to create a DJ Request Song Wish List. Anyone who can help me out will be saving me from severe insanity. :)

My goal is to:

1. Display search results for song title, artist and genre. (accomplished)
2. Allow the user to add songs to their Wish List. This is done by displaying checkboxes with the corresponding value equal to the songID. (working on it)
3. Allow the user to update their wishlist by adding/deleting songs.

So far I have a form that retrieves the song info from a database in a repeating region. In Dreamweaver:

<input name="songID[]" type="checkbox" id="songID[]" value="<b><?php echo $row_RecordsetSearchResults['Title'];?></b> by <?php echo $row_RecordsetSearchResults['Artist'];?>">

This puts the corresponding songID number into a checkbox value, which in turn is submitted by form POST action to the following page as an array.

To process this array I have:

if(isset($_POST['songID']))
{
$songID = $_POST['songID'];

print '<p>Song IDs:</p>'
// process items
$n = count($songID);
for($i = 0; $i <= $n; $i++)
{
//See if the values are being passed from POST
echo $songID[$i];
echo '<br>'
}
$songsInsert = '*'.implode('*',$_POST['songID']).'<br>'
$insertSQL = sprintf("INSERT INTO wishlist (Username, Title) VALUES (%s, %s)",
GetSQLValueString($MM_Username, "text"),
GetSQLValueString($songsInsert, "text"));

mysql_select_db($database_ToneDeaf, $ToneDeaf);

$Result1 = mysql_query($insertSQL, $ToneDeaf) or die(mysql_error());
}

The problem is, I'm using implode. It does store the songs, but only as one long block of text. So if the user picks "New York by Frank Sinatra" and "Hot In Here by Nelly" it is stored as "*New York by Frank Sinatra*Hot In Here by Nelly*" Obviously this gives me no options to make this actually readable, let alone allow the user to remove one of those songs from their list (both would be have to be removed.)

Also, referencing only the songID number as stored in the music database doesn't seem a good option, since the song database will be changing frequently and song data may be overwritten. Not sure if there's a viable workaround there.

Originally I wanted to store Title, Artist, Genre under seperate columns so I could link them to something like "See more songs from this Artist." However the more I read about arrays and multidimensional arrays, I realize I'm not ready to go there yet. (I just started learning PHP two weeks ago.)

Comparing Values Of 2 Arrays Combined With Mysql Field Names
I am trying to create an edithistory table that has a text column into which I will put a string that can be read using strtok later to revert changes if necessary. I want to build this function so that it's dynamic enough to be applied to every table so that I don't have to write one for each table that might be updated.

When a row is added to any table (a new entry), it retrieves the next available editid # from the edithistory table and assigns it to that item in the "edits" column for its row in its own table. Every edit made is a new entry in the edithistory table (entryid auto_increment primary key), and the editid is a reference back to the object being edited. Code:

Multiple <TD>'s And <TR>'s From MySQL?
I have a test table with say, a name and address. I want them to display in 3 columns across (or 5 or 6, whatever) and as many rows as necessary till my $result is empty.

Here's my code which obviously gets the the WHILE statement and prints all the addresses in <TD>'s in one <TR>. How do I get it to go 3 across, end the row, then continue..? Code:

Multiple Mysql Connections To The Same Db?
I know from reading on php.net that there is a boolean value you can set in mysql_connect() so that it will create a new link each time, even with the same arguments. But how do you specify which connection to use in your mysql_query (s)?
PHP Code:

Select Multiple & Mysql
What's the sql should look like to get all possible data when using multiple select,
such as: <select name="hostfield[]" multiple> PHP Code:

Multiple Mysql Objects
I have a system which needs to connect to two separate databases. I've created a class to handle my database connections but one thing i've ran into is that calling a second instance of a class will overwrite my previous database connection. Example.

My 2 databases have tables titled orders. Database A has 20 orders and Database B has 40. I call my mysql objects.

$mysqlObjA = new mysql($sqlhost,$sqluser,$sqlpass,$dbA);
$mysqlObjB = new mysql($sqlhostB,$sqluserB,$sqlpassB,$dbB);

then i execute my queries. Code:

Multiple MySQL Tables
I need some help with tables in MySQL.
I am making a colums of articles in my site.
It has 3 posters that post articles.
I make a little serach page to search for words into articles.

I have the sintax below working, but I need to know what is the syntax
to it select words from several tables. Every table is for a poster
and all tables are in the same DB and have the same fields.

---------------
$searchword="SELECT * FROM table WHERE comment LIKE
'%$searchstring%'";
---------------

I tried
---------------
$searchword="SELECT * FROM table, table1, table2 WHERE selected_row
LIKE '%$searchstring%'";
---------------

and even make an ARRY for table, table1, table2 but it does not work.

Multiple Mysql Row Updates
I'm trying to update multiple rows in a mysql database. I'm having no problem selecting data from the database and displaying it in the form.  I've even found a fairly straight forward script that is supposed to do what I need, BUT, when I submit the form (with changes), the update information is not working.

It appears that the code is failing at/or before the if($Submit){.  FYI, the fields I'm attempting to insert are decimal values (if that matters).  Am I missing something?? Please see the entire script, below: Code:

Multiple Queries To MySQL
I am querying each column twice; once to see how many people said 'Yes' to that question, and again to see how many people said 'no' to that question. This means a total of 38 queries. Is this the right way to do it or is there a better way? Like just one BIG query? Code:

Multiple Queryes For One Row MYSQL
Im making a reward system for my users and have a section in my user information section which is reward. but how could i add multiple parts of it. so like it would could have more than one reward. How could this be done?

Multiple Uploads Into Mysql
i have a page where users can select 1-5, this indicates how many files they want to upload, im used to just dealing with 1 upload at a time, i was wondering how i would go about inputting multiple entries into mysql also my input name will be different i take it aswell eh currently its: Code:

Php (or Mysql?) Multiple Sessions
I'm running a script that uses a mysql connect to my local database. The script runs on my local webserver (using wampserver).

When I'm running one instance of the script, and I'm trying to start another one, it won't start until the first script is finished.

When I run one session on FireFox and the other on Internet Explorer, it does work.

Is there some setting I need to change to allow more then one session?

Searching For Multiple Words In Mysql
I've got a table containing three columns:

Region (these are 8 predetermined values)
Club Name (an open text field which always contains more than one word)
url (contains a url)

On my search page I have two fields that can be used. The first is a drop down box with the regions in, and the other is an open text field searching the clubname field.

I would like to be able to search the table by either:

1. selecting the region on it's own (this works at the moment!!)
2. selecting a region and either one or more keywords (this works if the keyword is the first word in the clubname field in the database)
3. leaving the region blank (on the null value) and entering one or more keywords;

This is the current code:

<?php
mysql_connect (localhost, username, password);
mysql_select_db (swimclub_db);
if ($region == "")
{$region = '%'}
if ($club_name == "")
{$club_name = '%'}
$result = mysql_query ("SELECT * FROM clubs
WHERE region LIKE '$region%'
AND club_name LIKE '$club_name%'
");

if ($row = mysql_fetch_array($result)) {
do {
print $row["region"];
print (" ");
print $row["club_name"];
print (" ");
print $row["url"];
print ("<p>");
} while($row = mysql_fetch_array($result));
} else {print "Sorry, no records were found!";}
?>

Also, if I want the results to appear within my site template (particularly within a certain table) can I add the php code within the opened table and close the table at the end of the php?

Having Multiple Sort Options For A MySQL DB
I was wondering how you can sort MySQL rows in several different ways on one page using PHP. For instance, so that a user can click on a hyperlink to sort alphabetically, by price, by category, etc. Also, is it necessary to index each field in phpmyadmin that I want to sort?

Selecting From Multiple Tables In MySQL.
I need help in trying to retrieve information from different tables, each one having a different primary key (auto-increment).

I have 3 pages, each accessing their respective tables.

(TABLE_internet_arts)
TagID (PK)
name
email
message
date
ip
time
profile_id
site_url
image_url
msg_type
site_title
page_title

(TABLE_losangeles_arts)
TagID (PK)
name
email
message
date
ip
time
profile_id
site_url
image_url
msg_type
site_title
page_title

(TABLE_sanfrancisco_arts)
TagID (PK)
name
email
message
date
ip
time
profile_id
site_url
image_url
msg_type
site_title
page_title

Right now, for each table on it's own, the SELECT statement looks like the following:

SELECT * FROM internet_arts ORDER BY TagID DESC LIMIT $offset, $rowsPerPage";

What I want to do is take the messages from all 3 tables and have them displayed, ordering them in chronological order by the date & time posted onto one page.

Anyone know the correct syntax and how to make the SELECT statement to do this?

MySQL Multiple Tables / Results
I would like to perform multiple queries to a MySQL database and have all
the results in 1 result set.


Copyright © 2005-08 www.BigResource.com, All rights reserved