Mysql foreach массив php

How to store values from foreach loop into an array?

Need to store values from foreach loop into an array, need help doing that. The code below does not work, only stores the last value, tried $items .= . but that is not doing the trick either, any help will be appreciated.

foreach($group_membership as $i => $username) < $items = array($username); >print_r($items); 

9 Answers 9

Declare the $items array outside the loop and use $items[] to add items to the array:

$items = array(); foreach($group_membership as $username) < $items[] = $username; >print_r($items); 

what would happen if some of the $username are null? We have a similar situation where records are coming form an API, and somehow we are ending up with some null records in the array.

Can you help explain why you have to declare $items = array(); before the loop. I did something like this and didn’t declare it and it still works. Is it better to add it or is it not required?

$items = array_values ( $group_membership ); 

I am going to hold off on downvoting this answer although: 1. It is a code-only answer that 2.Teaches developers unnecessary/bad practices . because this is a great chance to do the Disciplined thing and make Stackoverflow a better resource.

I have issue where my array returns only last element that was pushed into array. Using count as suggested by you resolved my issue.

Читайте также:  Add href with css

You can try to do my answer,

And in your case I would do this:

 ' before $username $items[] = $username; > ?> 

As you show in your question it seems that you need an array of usernames that are in a particular group 🙂 In this case I prefer a good sql query with a simple while loop 😉

while is faster, but the last example is only a result of an observation. 🙂

Источник

PHP / MYSQL Insert Array Foreach Loop

This one has me pretty rattled so I thank you in advance for your assistance. There seem to be a number of walkthroughs on this topic but it seems I may be skinning this cat a bit different. . . . I have a purchase order form that I’m using javascript to dynamically add rows to a table and capture data for multiple line items. I’m then collecting data for each column in an array. For example I have «Cust_PN», «Qty», «Price» as columns and arrays for each. . . Cust_PN[0] Cust_PN[1] and Cust_PN[2] for line items 1-3 respectively. I then have Qty[0], Qty[1], and Qty[2] and so on. I can get this to echo properly without issue. However, when I go to post I am only posting the array data from the last entry *[3] per my example above. I currently have the following code/query. . . again any help would be much appreciated.

$query1 = "INSERT INTO SO_Items (Timestamp,SO_Num,SO_Rev,SO_Line_Item,Cust_PN,Cust_PN_Rev,My_PN,My_PN_Rev,Description, Qty,Sale_Price,UOM,Program,Required_Date) SELECT NOW(),'$SO_Num','$SO_Rev','$SO_Line_Item[$a]','$Cust_PN[$a]','$Cust_PN_Rev[$a]','$My_PN[$a]','$My_PN_Rev[$a]','$Description[$a]','$Qty[$a]','$Sale_Price[$a]','$UOM[$a]','$Program[$a]','$Required_Date[$a]'" or die ('Error posting data'); foreach($Cust_PN as $a => $b)

2 Answers 2

Your main issue is, declaring $query outside the loop. It makes it a constant, and that too, takes values $a and $b which are that time, undefined, so results in invalid syntax for SQL.

Try that. Fixed your SQL query too. Correct syntax is

INSERT INTO table_name (column1, column2, column3. ) VALUES (value1, value2, value3. ) 

You had put SELECT in place of VALUES

Let me know if it works, and otherwise please tell what error it ives exactly.

Источник

PHP Array ForEach SQL Query

I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.

//Decode JSON file to an Object $json_d = json_decode(file_get_contents("results.json")); //Provisional Array Setup for Grades $grade = array(); $userid = array(); foreach($json_d->assignments[0]->grades as $gradeInfo) < $grade[] = $gradeInfo->grade; $userid[] = $gradeInfo->userid; > //Server Details $servername = "localhost"; $username = "root"; $password = ""; $dbname = "moodle"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) < die("Connection failed: " . mysqli_connect_error()); >echo ""; foreach($userid as $id) < foreach($grade as $grd) < $sql = "SELECT firstname, lastname FROM mdl_user WHERE "; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) >0) < // output data of each row while($row = mysqli_fetch_assoc($result)) < echo ""; > > else < echo "ERROR!"; >> > echo "
First Name Last Name Grade
" . $row["firstname"]. "" . $row["lastname"]. " " . $grd . "
"; mysqli_close($conn);

I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G. FirstName LastName Grade
Student 1 85 Whereas I need the other 2 records that are supposed to appear.

$userid is an array, having the following values [0]=3,[1]=4,[2]=5. I can confirm these values exist in the database (table)

Are you sure? can you please put a var_dump($userid); before this line $servername = «localhost»; and share the output with us? Also having 2 nested foreach loops is wrong and will output wrong result for you.

Источник

PHP Foreach on MySQLi Result set

I have this chunk of code which works on my local XAMPP testing server. The problem is, when pushed to the production server, it breaks. This isn’t an issue with the database connection, and PHP/MySQL are both at 5.3 on the production server so it isn’t the use of old versions of either. I’m thinking it’s the use of the foreach loop instead of the more standard while loop; if it’s that, why?

EDIT: To clarify, it breaks by not outputting anything at all; when inserting a simple echo statement inside the loop, it seems to not even execute it. EDIT2: I’ve added an answer below which goes into slightly more detail about what the problem here actually was and why this code does actually work under certain conditions.

check phpinfo and make sure the extension for mysql is enabled, and add some error checking to your code

@ManseUK: I’ve checked that, and yes MySQL is enabled. There was error checking before, but now it’s been removed to keep this algorithm as simple as possible.

You need to $res->fetch_assoc() from that. You can’t iterate the result resource, as it isn’t an array. php.net/manual/en/mysqli-result.fetch-assoc.php

2 Answers 2

So since I asked this question ages ago I figure I should update it with some additional clarification by saying this: what I did first with the foreach loop does work. The caveat being that it only works in PHP 5.4+ as that’s when the mysqli_result class implemented the Traversable interface. This means you can iterate over it using a foreach loop in later versions of PHP.

This change apparently wasn’t super well-known at the time I posted my question (mid-2013) likely due to the fact that so many servers across the internet still use 5.3—likely because that’s the latest version of PHP available to Ubuntu 12.x—which limits its utility to recently updated servers. But when you’re in an environment that supports it this is a totally valid technique to use.

Источник

Create Array from Foreach

I have a Mysql table which contains a column of JSON data and a column with an amount. The goal is to extract the JSON data and the amount and build an array within the foreach loop. Here is my code:

$sql = "SELECT `Amount`, `NewObject` FROM `mb_cart` WHERE `MyID` = '$id'"; $data_main = $db->query($sql); 
foreach ($data_main as $transaction_main) < $json_decoded = json_decode($transaction_main); $cart = array('Amount' =>$amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName); > 

However when I run this, I am only returning only the first record set and the amount is blank, but the JSON data is listed. Appreciate any insight anyone cares to share.

What does $db->query($sql); return? An array or an iterator? See also array_push and the note there, foreach with a reference and iterator_to_array .

5 Answers 5

You need to add [] to $cart array. WIth each run of foreach you’re overwriting the variable $cart.

something like so would work:

foreach ($data_main as $transaction_main) < $json_decoded = json_decode($transaction_main); $cart[] = array('Amount' =>$amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName); > 

Or if you wanted the array key to match that of the ID of each row:

Note: You will need to set $id variable somehow above IE: SELECT id, amount also note that you COULD potentially have issues if integer from id is non-unique.. eg(1,1,2,3,4,5,6) it will only show the last id of 1 instead of both (since key’s are duplicates).

foreach ($data_main as $transaction_main) < $json_decoded = json_decode($transaction_main); $cart[$id] = array('Amount' =>$amount, 'CodeType' => $json_decoded->data->Type->data->codeType, 'Name' => $json_decoded->data->Name, 'SiteName' => $json_decoded->data->SiteName); > 

Источник

Оцените статью