Unsetting an item from an array in a session - php

I am trying to remove an item from my array in a stored session. I have attempted the following but it reverses and actually adds more!
So here is my foreach where the product shows in the cart with a button to remove from the cart:
foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];
echo '<a href="single_product.php?product_id=' . $product['products'] . '">';
echo "<img src='$img'><br />";
echo "Product: $name<br />";
echo "Price: $price | ID: $id<br />";
echo "$description";
echo '</a><br /><br />';
echo '<form action="removeItem.php" method="post">
<input type="hidden" name="product_id" value="' . $product['id'] . '" />
<button name="removeItem">Remove</button>
</form>';
$sum += $price;
}
And here is the form to remove it but it actually adds more when you hit remove:
$_SESSION['products'][] = $itemid;
$id = $_POST['id'];
unset($_SESSION['products'][$id]);
header("location:basket.php");

Try something like this:
$product_id = $_POST["id"];
foreach($_SESSION['products'] as $key=>$product) {
if($product['id'] == $product_id) {
unset($_SESSION['products'][$key]);
break;
}
}

Related

Storing multiple items into a session

I am trying to store multiple items into a session. I am posting an items from a form like so:
<?php
$product_id = $_GET['product_id'];
$sql = "SELECT * FROM Products WHERE product_id = $product_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<img src=' . $row['product_img'] . ' />';
echo '<div class="title">'. $row['product_name'] .'</div>';
echo '<div class="title">'. $row['product_price'] .'</div>';
echo '<div class="title">'. $row['product_sku'] .'</div>';
echo '<div class="title">'. $row['product_description'] .'</div>';
echo '<form action="addToCart.php" method="post">
<input type="hidden" name="product_img" value="' . $row['product_img'] . '" />
<input type="hidden" name="product_id" value="' . $row['product_id'] . '" />
<input type="hidden" name="product_name" value="' . $row['product_name'] . '" />
<input type="hidden" name="product_price" value="' . $row['product_price'] . '" />
<input type="hidden" name="product_sku" value="' . $row['product_sku'] . '" />
<input type="hidden" name="product_description" value="' . $row['product_description'] . '" />
<input type="submit" name="Submit">
</form>';
}
} else{
echo "0 Results";
}
?>
addToCart.php looks like this:
<?php
if (isset($_POST['Submit'])) {
$_SESSION['product_img'] = $_POST['product_img'];
$_SESSION['product_id'] = $_POST['product_id'];
$_SESSION['product_name'] = $_POST['product_name'];
$_SESSION['product_price'] = $_POST['product_price'];
$_SESSION['product_sku'] = $_POST['product_sku'];
$_SESSION['product_description'] = $_POST['product_description'];
}
?>
So the above is now setting the items into the session (So I believe). I am then outputting the item from the stored data in basket.php
<?php echo '<img src=' . $_SESSION['product_img'] . ' />'; ?>
<?php echo $_SESSION['product_id'];?>
<?php echo $_SESSION['product_name'];?>
<?php echo $_SESSION['product_price'] ?>
<?php echo $_SESSION['product_sku']; ?>
<?php echo $_SESSION['product_description']; ?>
the Issue I have is whenever I add another item it overrides the previous item? I know I need to use an array to store multiple items but I have tried a few different things but I am struggling to understand.
You can use [] to store them in array:
$_SESSION['product_img'][] = $_POST['product_img'];
$_SESSION['product_id'][] = $_POST['product_id'];
$_SESSION['product_name'][] = $_POST['product_name'];
$_SESSION['product_price'][] = $_POST['product_price'];
$_SESSION['product_sku'][] = $_POST['product_sku'];
$_SESSION['product_description'][] = $_POST['product_description']
Now, try to see what are in each array:
var_dump($_SESSION['product_id']);
It is possible to store your Session Data as nested array. In your case, since it is a Shopping Cart, you may want to build your Arrays using the ID of the Product; that way you are certain that no product will override the other (so long as they don't have the same product_id values.... Below is an example of how you may do that:
<?php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
if (isset($_POST['Submit'])) {
$product_id = htmlspecialchars(trim($_POST['product_id']));
$product_img = htmlspecialchars(trim($_POST['product_img']));
$product_sku = htmlspecialchars(trim($_POST['product_sku']));
$product_name = htmlspecialchars(trim($_POST['product_name']));
$product_price = htmlspecialchars(trim($_POST['product_price']));
$product_description = htmlspecialchars(trim($_POST['product_description']));
if(!isset($_SESSION['products'])){
$_SESSION['products'] = array();
}
if(!isset($_SESSION['products'][$product_id])){
$_SESSION['products'][$product_id] = array();
}
$_SESSION['products'][$product_id]['product_id'] = $product_id;
$_SESSION['products'][$product_id]['product_img'] = $ $product_img;
$_SESSION['products'][$product_id]['product_name'] = $product_name;
$_SESSION['products'][$product_id]['product_price'] = $product_price;
$_SESSION['products'][$product_id]['product_sku'] = $product_sku;
$_SESSION['products'][$product_id]['product_description'] = $product_description;
}
And anywhere else (another Script perhaps) you could access your Data like so:
<?php
$output = "";
$storedProductData = $_SESSION['products'];
if(!empty($storedProductData)){
foreach($storedProductData as $product_id=>$productData){
$output .= "<img src='{$productData['product_img']}' />" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_id']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_name']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_price']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_sku']}</span>" . PHP_EOL;
$output .= "<span id='generic-class'>{$productData['product_description']}</span>" . PHP_EOL;
}
}

MySQLi and PHP sends only single products on the database

I can't find where is the problem at my code. It only send single orders to the database. When I order in my cart 2 or more than items, it only sends the last order. I don't have any idea how I can change or add some syntax in my code.
Here is my code in checkout.php
<?php
session_start();
echo '<h3>Your Order</h3>';
$current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION['products'])){
echo '<ol>';
echo '<form action="checkout_with_us.php" method="POST">';
$total = 0;
$cart_items = 0;
foreach($_SESSION['products'] as $cart_itm){
$product_code = $cart_itm['code'];
$results = $mysqli->query("SELECT product_name,product_desc,price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li>';
echo 'Price: '.$currency.$obj->price;
echo '<h4>'.$obj->product_name.'(Code: '.$product_code.')</h4>';
echo 'Qty: '.$cart_itm['qty'];
echo '</li>';
$subtotal = ($cart_itm['price'] * $cart_itm['qty']);
$total = ($total + $subtotal);
$cart_items++;
echo '<input type="hidden" name="item_name" value="'.$obj->product_name.'">';
echo '<input type="hidden" name="item_desc" value="'.$obj->product_desc.'">';
echo '<input type="hidden" name="item_qty" value="'.$cart_itm["qty"].'">';
echo '<input type="hidden" name="item_code" value="'.$product_code.'">';
}
echo '<strong>Sub Total: '.$currency.$total.'</strong>';
echo '<input type="hidden" name="price" value="'.$total.'">';
echo '</ol>';
}
//Here is the information of the customer
echo 'Firstname: <input type="text" name="firstname"><br />';
echo 'Lastname: <input type="text" name="lastname"><br />';
echo 'Email: <input type="text" name="email"><br />';
echo '<input type="submit" value="Send Step">';
echo '</form>';
?>
And here is my checkout.with_us.php codes. This code is the bridge to send the information to the database.
<?php
session_start();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$order_name = $_POST['item_name'];
$order_code = $_POST['item_code'];
$order_qty = $_POST['item_qty'];
$sub_total = $_POST['price'];
$conn = mysqli_connect('localhost','root','','sampsix')or die('Could not connect');
$query = "INSERT INTO `sampsix`.`orders`(`firstname`,`lastname`,`email`,`OrderName`,`OrderCode`,`OrderQty`,`SubTotal`) VALUES('$firstname','$lastname','$email','$order_name','$order_code','$order_qty','$sub_total')";
mysqli_query($conn,$query);
mysqli_close($conn);
header('Location: checkout.php');
?>
Delete your other question, ok?
The problem is you loop through $_SESSION and use the same name value each time. You need to create an array of your inputs. Here is an example:
<?php
echo '<h3>Your Order</h3>';
$current_url = base64_encode($url='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION['products'])){
echo '<ol>';
echo '<form action="checkout_with_us.php" method="POST">';
$total = 0;
$cart_items = 0;
foreach($_SESSION['products'] as $cart_itm){
$product_code = $cart_itm['code'];
$results = $mysqli->query("SELECT product_name,product_desc,price FROM products WHERE product_code='$product_code' LIMIT 1");
$obj = $results->fetch_object();
echo '<li>';
echo 'Price: '.$currency.$obj->price;
echo '<h4>'.$obj->product_name.'(Code: '.$product_code.')</h4>';
echo 'Qty: '.$cart_itm['qty'];
echo '</li>';
$subtotal = ($cart_itm['price'] * $cart_itm['qty']);
$total = ($total + $subtotal);
$cart_items++;
echo '<input type="hidden" name="product['.$product_code.'][item_name]" value="'.$obj->product_name.'">';
echo '<input type="hidden" name="product['.$product_code.'][item_desc]" value="'.$obj->product_desc.'">';
echo '<input type="hidden" name="product['.$product_code.'][item_qty]" value="'.$cart_itm["qty"].'">';
echo '<input type="hidden" name="product['.$product_code.'][item_code]" value="'.$product_code.'">';
}
echo '<strong>Sub Total: '.$currency.$total.'</strong>';
echo '<input type="hidden" name="product['.$product_code.'][price]" value="'.$total.'">';
echo '</ol>';
}
//Here is the information of the customer
echo 'Firstname: <input type="text" name="firstname"><br />';
echo 'Lastname: <input type="text" name="lastname"><br />';
echo 'Email: <input type="text" name="email"><br />';
echo '<input type="submit" value="Send Step">';
echo '</form>';
?>
You can catch this by looping in your product array:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$conn = mysqli_connect('localhost','root','','sampsix')or die('Could not connect');
foreach($_POST['product'] as $product)
{
$order_name = $product['item_name'];
$order_code = $product['item_code'];
$order_qty = $product['item_qty'];
$sub_total = $product['price'];
$query = "INSERT INTO `sampsix`.`orders`(`firstname`,`lastname`,`email`,`OrderName`,`OrderCode`,`OrderQty`,`SubTotal`) VALUES('$firstname','$lastname','$email','$order_name','$order_code','$order_qty','$sub_total')";
mysqli_query($conn,$query);
}
mysqli_close($conn);
header('Location: checkout.php');
?>
I don't know what the purpose is of the table orders but with my example the products will be added to this table with the same firstname, lastname, etc.

update quantity with one button php

Hello i am currently doing a project to make a website that sells game however one of my problems right now is updating the quantity with a single button. i have got it working with multiple update buttons next to the items that i would like to update but to make it more realistic, i would like to just have one button that will update all the item quantities in the basket table in my database.
This is my cart file, i have commented out the bit where it works with multiple update buttons.
<?php
$count = 0;
while ($count < $numrow)
{
$row = $results -> fetch_assoc();
extract($row);
echo"<div>";
echo"<div class='recommended_games'>";
echo "<img src='images/".$gameIMG."' />";
echo "</div>";
echo '<div class="price_tag">';
echo '<div class="price_tag">£'.$gamePrice. '</div>';
echo'</div>';
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform" id="update_all">';
echo '<select name="quantity" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
//echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" />';
//echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo '</form>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<input type="hidden" value="'.$gameID.'" name="gameid" id="gameid" form="update_all"/>';
echo '<input type="submit" value="update" form="update_all"/>';
?>
This is my updatebasket file which updates the quantity in the database
<?php
session_start();
require "dbconnect.php";
$memberID = $_SESSION['id'];
$quantity = $_POST['quantity'];
$gameID = $_POST['gameid'];
$connect->query($query);
$query = "UPDATE basket SET quantity = ".$quantity." WHERE gameid = ".$gameID." AND id = ".$memberID."";
$results = $connect->query($query);
mysqli_commit($con);
header('Location: cart.php');
?>
If I understand you correctly, you need to work with an array for this to be achieved, by changing your form and you can use a foreach to assemble your query to update each entry in the cart. So one button will update each item in the cart with the respective quantities. I did not test this code, this is how I would approach it.
Eample of the HTML Form Changes:
echo '<div id="update_form"><form action="updatebasket.php" method="POST" name="updateform" id="update_all">';
echo '<select name="quantity[]" id="quantity" />';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '</select>';
//echo '<input type="hidden" value="'.$gameID.'" name="gameid[]" id="gameid" />';
//echo '<input type="submit" value="update" />';
echo '</form>';
echo '</div>';
echo '</form>';
echo"<img class='box1' src='Images/Grey-Banners.png' />";
echo"</div>";
$count = $count + 1;
}
echo '<input type="hidden" value="'.$gameID.'" name="gameid[]" id="gameid" form="update_all"/>';
echo '<input type="submit" value="update" form="update_all"/>';
?>
Query Eample:
foreach ($_POST['gameid'] as $row=>$id) {
$gameid = $id;
$newquantity = ($_POST['quantity'][$row]);
$query = "UPDATE basket SET quantity = ".$newquantity." WHERE gameid = ".$gameID." AND id = ".$memberID."";
$connect->query($query);
}
One solution would be to give your quantity <select> inputs unique names with the Game ID attached to the end (eg. "quantity_32"). This makes it easy to know how much of each game is in the cart.
// POST Example
$_POST['quantity_32'] = 1;
$_POST['quantity_31'] = 3;
$_POST['quantity_37'] = 2;
Front-End Form Change
echo '<select name="quantity_<?=$gameID?>" id="quantity" />';
Back-End Processing
Then on the processing page loop through the $_POST variables and find the quantity fields and grab their Game ID's.
foreach ($_POST as $key => $quantity) {
// Ignore non-quantity fields
if (preg_match('/quantity_([0-9]+)/i', $key, $result) !== 1) continue;
$quantity = (int)$quantity;
$game_id = (int)$result[1];
// Update Cart Quantity in DB
// ...
}
Important!
Please ensure you SQL-Escape all values you save into the DB. Hackers could do some nasty stuff if you don't.
This example shows how you can keep things safe using MySQLi Prepared Statements.
http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/

The only int variable won't _POST

And I again I have to deal with PHP and MySQL :) So, I've got a mysql table and want to have "add" feature. So I can edit my table from browser easily. So far I have done nearly everything but the problem is that variable consisting "number" from my table (or id) won't _POST to other page. It won't _POST directly from textarea or even if I put it in a hidden field(well, have just understood that this is pretty much the same).
Let me show you some examples:
$a = mysql_query("SELECT number FROM peoples ORDER BY number DESC LIMIT 1");
$number_a = mysql_fetch_assoc($a);
$number = $number_a['number']+1;`
That's how I got this variable.
echo '<input name="id" type="hidden" value="'.$number.'" />';
That's how I pass it.
echo $number = mysql_escape_string( $_POST['id'] );
That's how I tried to get it in other php file.
Everything from other textareas passes just fine.
Full code as requested. ADD.PHP:
<?php
$dblocation = "127.0.0.1";
$dbname = "tvp";
$dbuser = "root";
$dbpasswd = "";
$dbcnx = #mysql_connect($dblocation,$dbuser,$dbpasswd);
if (!$dbcnx)
{
echo( "<P>В настоящий момент сервер базы данных не доступен, поэтому
корректное отображение страницы невозможно.</P>" );
exit();
}
if (!#mysql_select_db($dbname, $dbcnx))
{
echo( "<P>В настоящий момент база данных не доступна, поэтому
корректное отображение страницы невозможно.</P>" );
exit();
}
echo '<form name="editform" action="adder.php" method="POST">';
echo '<table>';
echo '<tr>';
echo '<td>Номер</td>';
$a = mysql_query("SELECT number FROM peoples ORDER BY number DESC LIMIT 1");
$number_a = mysql_fetch_assoc($a);
$number = $number_a['number']+1;
echo $number;
var_dump($number);
print_r($number);
echo '<td><textarea name="number" >'.$number.'</textarea></td>';
echo '<input name="id" type="hidden" value="'.$number.'" />';
echo '</tr>';
echo '<tr>';
echo '<td>Имя</td>';
echo '<td><textarea name="givenName">'.$man['givenName'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Инициалы</td>';
echo '<td><textarea name="middleInitial">'.$man['middleInitial'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Фамилия</td>';
echo '<td><textarea name="surname">'.$man['surname'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Пол</td>';
echo '<td> <input type="radio" name="gender" value=1 >Man<Br>
<input type="radio" name="browser" value=0>Woman<Br> </td>';
echo '</tr>';
echo '<tr>';
echo '<td>Город</td>';
echo '<td><textarea name="city">'.$man['city'].'</textarea></td>';
echo '</tr>';
echo '<input name="id" type="hidden" value="'.$id.'" />';
echo '<input name="statee" type="hidden" value="'.$man['state'].'" />';
echo '<tr>';
echo '<td>Штат</td>';
?>
<td><select size="3" name="state">
<option disabled>Выберите штат</option>
<option value="AL"
<?php
if($man['state']=="AL"){
echo "selected";
}?>
>Alabama
</option>
//...and so on...
</select></td>
<?php
echo '</tr>';
echo '<tr>';
echo '<td>Телефон</td>';
echo '<td><textarea name="telephone">'.$man['telephone'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>E-mail</td>';
echo '<td><textarea name="emailAddress">'.$man['emailAddress'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Дата</td>';
echo '<td><textarea name="birthday">'.$man['birthday'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Место работы</td>';
echo '<td><textarea name="occupation">'.$man['occupation'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Компания</td>';
echo '<td><textarea name="company">'.$man['company'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Вес</td>';
echo '<td><textarea name="weight">'.$man['weight'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Рост</td>';
echo '<td><textarea name="length">'.$man['length'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Адрес</td>';
echo '<td><textarea name="streetAddress">'.$man['streetAddress'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Почтовый индекс</td>';
echo '<td><textarea name="zipCode">'.$man['zipCode'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td>Страна</td>';
echo '<td><textarea name="country">'.$man['country'].'</textarea></td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="submit" value="Сохранить"></td>';
echo '<td><button type="button" onClick="history.back();">Отменить</button></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
?>
And ADDER.PHP:
<?php
$dblocation = "127.0.0.1";
$dbname = "tvp";
$dbuser = "root";
$dbpasswd = "";
$dbcnx = #mysql_connect($dblocation,$dbuser,$dbpasswd);
if (!$dbcnx)
{
echo( "<P>В настоящий момент сервер базы данных не доступен, поэтому
корректное отображение страницы невозможно.</P>" );
exit();
}
if (!#mysql_select_db($dbname, $dbcnx))
{
echo( "<P>В настоящий момент база данных не доступна, поэтому
корректное отображение страницы невозможно.</P>" );
exit();
}
$number=$_POST["id"]; echo '<br>';
var_dump($_POST['id']);
print_r($POST['id']);
echo $number;
echo $givenName = mysql_escape_string( $_POST['givenName'] ); echo '<br>';
echo $middleInitial = mysql_escape_string( $_POST['middleInitial'] ); echo '<br>';
echo $surname = mysql_escape_string( $_POST['surname'] ); echo '<br>';
echo $gender = $_POST['gender'] ; echo '<br>';
echo $city = mysql_escape_string( $_POST['city'] ); echo '<br>';
echo $state = mysql_escape_string( $_POST['state'] );echo '<br>';
echo $emailAddress = mysql_escape_string( $_POST['emailAddress'] ); echo '<br>';
echo $telephone = mysql_escape_string( $_POST['telephone'] ); echo '<br>';
echo $birthday = mysql_escape_string( $_POST['birthday'] ); echo '<br>';
echo $occupation = mysql_escape_string( $_POST['occupation'] );echo '<br>';
echo $company = mysql_escape_string( $_POST['company'] ); echo '<br>';
echo $weight = mysql_escape_string( $_POST['weight'] ); echo '<br>';
echo $length = mysql_escape_string( $_POST['length'] ); echo '<br>';
echo $streetAddress = mysql_escape_string( $_POST['streetAddress'] ); echo '<br>';
echo $zipCode = mysql_escape_string( $_POST['zipCode'] ); echo '<br>';
echo $country = mysql_escape_string( $_POST['country'] ); echo '<br>';
$query = "INSERT INTO peoples (number,givenName, middleInitial, surname, gender, city, state, emailAddress, telephone, birthday, occupation, company, weight, length, streetAddress, zipCode, country) VALUES ( '".$number."', '".$givenName."', '".$middleInitial."', '".$surname."', '".$gender."', '".$city."', '".$state."', '".$emailAddress."', '".$telephone."', '".$birthday."', '".$occupation."', '".$company."', '".$weight."', '".$length."', '".$streetAddress."', '".$zipCode."', '".$country."');";
mysql_query ( $query );
?>
Thanks in advance!
first things first. make sure you are echoing out the number to the screen. the code you have written looks correct but it's just a snippet.
add var_dump($number) after you assign your number and see if it's showing the number. if it's not then theres a problem with your sql
the problem is your re-assigning the hidden field id at the bottom of your form
here
echo '<td><textarea name="city">'.$man['city'].'</textarea></td>';
echo '</tr>';
echo '<input name="id" type="hidden" value="'.$id.'" />'; <------- HERE
echo '<input name="statee" type="hidden" value="'.$man['state'].'" />';
echo '<tr>';
echo '<td>Штат</td>';
i'm assuming you never assigned $id to number so, at the top of your form, yours assigning the hidden field id to "$number" but at the bottom of the form your assigning the hidden field id to $id. overwriting the original id field from the top of the form
You are echoing!
echo $number = mysql_escape_string( $_POST['id'] );
Change that with:
$number = mysql_escape_string( $_POST['id'] );
echo $number;
If you wanna echo it.

Invalid argument supplied for foreach() - Yet output is showing

I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the "Invalid argument supplied for foreach()" warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
Here is the code:
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' ORDER BY RECORD";
$data = mysqli_query($dbc, $query8);
echo '<pre>' . print_r($data, true) . '</pre>';
$rowcount = 1;
while ($row = mysqli_fetch_assoc($data))
{
if (is_array($row))
{
echo '<p> It is an Array</p>';
}
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
echo 'Rowcount' . $rowcount. '</br>';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ( (!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="major">Field of study:</label>';
echo '<input type="text" id="major" name="major" size="40" maxlength="40" value="' . ( (!empty($major)) ? $major : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
$rowcount++;
}
}
;
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
foreach ($row as &$item)
replace this with:
foreach ($row as $item)
And then for each variable you should probably change
$record = $row['RECORD'];
to
$record = $item['RECORD'];
foreach($row as &$item) should be
foreach($row as $item)
there is no need to use the foreach here you can just do this like like
while ($row = mysqli_fetch_assoc($data))
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
}
You're not changing the row item, so don't pass by reference to the foreach. Also, shouldn't you be using $item instead of $row? Do this:
foreach($row as $item)
{
$record = $item['RECORD'];
$school = $item['SCHOOL'];
....
Don't do This:
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
....

Categories