Unable to display all rows of mysql_fetch_array using while loop.
Hi. My problem is I am only able to display last row entered into database table.
I am parsing form data with php to insert into a database table.
I know that the form data is being inserted into the table.
I am using a while loop to attempt to extract data from two columns in all of the rows of the table.
I am using php to display the data of the two columns id & product_name in each row.
It is my understanding that a mysql_fetch_array will only return 1 row unless it is used in conjunction with a while loop, which then should return all rows. So I am confused why I can only out put the last row.
When I browse the table in phpMyAdmin there are three rows each with an id number.
They are ordered sequentially 1, 2, 3 because the id column is auto increment.
id column is primary key.
product_name column is unique key.
I don't think there is a problem with my query structure.
Possibly a problem defining $product_list variable ? I don't know.
I have closed browser and cleared all history, cookies etc.
I have stopped & restarted Apache server & mysql.
When I echo var_dump ($sql); I get: resource(6) of type (mysql result) .
When I echo var_dump ($product_list); I get: string(99) "3 - Blue Jeans edit • delete "
When I print_r ($sqL); I get: Resource id #6
When I echo $product_list; I get: 3 - Blue Jeans edit • delete
I have spent a lot of time searching for answer to this via google searches but none seem to fit this particular problem.
I did see one similar question suggesting using a concatenation approach, but there were zero (0) up-votes. So I wasn't sure if this was a viable remedy to my problem.
Here is the code I am using:
<?php
//this block grabs the whole list for viewing
$product_list = "";
$sql= mysql_query ("SELECT * FROM `products`");
$product_count = mysql_num_rows ($sql);
if ($product_count > 0) {
while($row = mysql_fetch_array ($sql)) {
$id = $row['id'];
$product_name = $row ['product_name'];
$product_list = "$id - $product_name <a
href='#'>edit</a> • <a href='#'>delete</a>
<br/>";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
<?php echo $product_list; ?>
You are overwriting $product_list in every loop.
You have to concateate by concat operator .=
$product_list .= "$id - $product_name <a href='#'>edit</a> • <a href='#'>delete</a> <br/>";
Ok this answer might not what you're looking for but I only use mySQLi not the older version. I'll rewrite the your code with the newer syntax only because I know this would work. So here goes
<?php
$conn = new mysqli($server, $username, $password, $database);
$product_list = "";
$sql = $conn->query("SELECT * FROM products");
$product_count = mysqli_num_rows ($sql);
if ($product_count > 0) {
while($row = $sql->fetch_assoc()) {
$id = $row['id'];
$product_name = $row ['product_name'];
$product_list = "$id - $product_name <a
href='#'>edit</a> • <a href='#'>delete</a>
<br/>";
}
} else {
$product_list = "You have no products listed in your store yet";
}
?>
You would need to either add the $conn = new mysqli($server, $username, $password, $database); in mySQLi Object Orientated method or can replace $conn on the $sql = $conn->query("SELECT * FROM products"); line withe your existing one and this should work.
Related
In this application I have a drop down so you can select what table you want to view. Using Ajax I push the variable $tbl as an integer and the code below prints out the table that corresponds with that integer. Something is not working though and I need an extra pair of eyes to help debug.
if($tbl == 9){$table = "person";}
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
$query = mysqli_query($conn, "SELECT * FROM $table ") or die(mysqli_error($conn));
if($query){
echo '<table border="1"><thead><tr>';
$colnames = array();
while ($finfo = mysqli_fetch_field($query)) {
$name=$finfo->name;
array_push($colnames, $name);
echo "<th>".$name."</th>";
}
mysqli_free_result($query);
echo '</tr></thead><tbody>';
$count = 0;
echo $colnames[$count]; // this test prints the correct column name but it ends up being printed OUTSIDE the table for some reason
while ($row = mysqli_fetch_array($query, MYSQLI_BOTH)){
echo '<td>'.$row[$colnames[$count]].'</td>';
$count++;
}
echo "</tbody></table>";
}
The last while loop is suppose to echo out each field value but it isn't executing <tbody> is left blank.
You called mysqli_free_result($query) too early. So by the time you called mysqli_fetch_array, the sql result was already gone. Move mysqli_free_result after the last loop.
I'm not sure whether it's a typo or that the following is where the problem lies, but you're missing opening and closing <tr> tags around the column names after <tbody> and before </tbody>. This may help explain why stuff is being printed apparently "outside" the table.
How can I update a database with the values from an array? For example, let’s say we got a database with three tables:
Meals:
mealnr(PK), name, sort
Ingredients: ingredientnr(PK), name, stock
Structure: mealnr(FK), ingredientnr(FK), amount
I filled the database with some meals and ingredients. Every meal consists of multiple ingredients. The chef decides you only need 75g of ingredient x instead of 100g for meal y, so it needs to be changed in the database. Of course it can be done with SQL-commands, but I want to do it using a form in PHP.
First I made a page where all the meals are displayed. A meal can be edited using the edit-button next to it and based on the mealnr, you can change the amount of one or multiple ingredients for that particular meal. On the edit-page all the ingredient names and amounts are displayed in a table. The amount fields are textfields, those can be edited.
I made this script, but I don’t know exactly how I can update my database with the values of an array. I tried it with a foreach-loop, but it doesn't work.. yet. Can somebody help me?
<?php
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db("eatit", $conn);
$id = $_REQUEST['mealnr'];
$result = mysql_query("SELECT meals.name AS mealname, structure.amount, ingredients.name AS ingredientname
FROM Meals, Structure, Ingredients
WHERE meals.mealnr = structure.mealnr
AND structure.ingredientnr = ingredients.ingredientnr
AND meals.mealnr = '$id'");
if(isset($_POST['save']))
{
$new_amount = $_POST['amount[]'];
foreach ($new_amount as $value) {
mysql_query("UPDATE structure SET amount ='$value', WHERE mealnr = '$id'")
or die(mysql_error());
}
}
mysql_close($conn);
?>
<p><strong>Ingredients:</strong></p>
<?php
echo "<table>";
echo "<tr>";
echo "<th>Ingredient</th>";
echo "<th>Amount (gr)</th>";
echo "</tr>";
while($ingredient = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>";
echo $ingredient['ingredientname'];
echo "</td>";
echo "<td>";
echo '<input type="text" formmethod="post" name ="amount[]" value="' . $ingredient['amount'] . '" />';
echo "</td>";
echo "</tr>";
}
?>
<input type="submit" name="save" value="save" />
In your HTML markup you have declared the elements holding the name amount as an array by using amount[].
So, in your php code that receives the data it's enough to just refer to the amounts this way:
$new_amount = $_POST['amount'];
instead of:
$new_amount = $_POST['amount[]']; // in fact, this is wrong
Your foreach is fine, you should add some checks so that the $value actually contains a value that you expect, for example an int, float or not less than zero (or whatever checks you find necessary).
foreach($new_amount as $value){
if($value != '' && $value >= 1){
//sql statements goes here.
}
}
Receiving form data this way and then directly injecting the result to your SQL statement is always dangerous:
$id = $_REQUEST['mealnr'];
If you declare that you expect an integer (as the id's should be) before you directly inject the code to your SQL statement you have already written safer code.
$id = (int)$_REQUEST['mealnr'];
Also, just for the record - the mysql_* library is deprecated. As pointed out in the comments, try using PDO or mysqli instead - really!
I got this list of checkboxes that print out from database. I am able to retrieve data from database if user makes multiple checkbox and display it in table, but i cannot retrieved other information from database and display it in the same table.
This is my code:
<table border='1'>
<tr>
<th>TITLE</th>
<th>PERCENTAGE RESULT</th>
</tr>
<?php
if(isset ($_POST["submit1"]))
{
$selectedcheckbox = $_POST["selectedcheck"];
$query = "SELECT * FROM compareresult where subject=$selectedcheckbox";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while($data = mysql_fetch_array($sql_query,MYSQL_ASSOC)){
$result=$data['result'];
}
foreach($selectedcheckbox as $title)
{
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
}
echo "</tr>";
}
?>
I want to display result after user select multiple checkbox, so I wrote:
echo $result in table
so that the result can be displayed in table beside the selected title, but I am getting an error:
Array to string conversion in C:\xampp\htdocs\sam\c.php on line 31 Error 3 :Unknown column 'Array' in 'where clause'
I am not at the moment in the environment to test your problem, and I do this out of my head, but try something like the following.
if(isset($_POST['submit1'])){
$checkbox = isset($_POST['selectedcheck']) ? $_POST['selectedcheck'] : array();
foreach($checkbox as $title){
$query = "SELECT * FROM compareresult where subject='".$title."'";
$result=mysql_query($query); // <-- to avoid SQL injections, please change your method from mysql_query to mysqli_query (use the mysqli functions instead of mysql)
while($data = mysql_fetch_array($result)){
$result=$data['result'];
echo "<tr>";
echo "<td>".$title."</td>";
echo "<td>".$result."</td>";
echo "</tr>
}
}
}
It checks first if your checkboxes are checked and if they are they put it in an array.
Then it runs the foreach statement, where it sets the checkbox value as title. It runs there if the query if it the title is in the database, if so, spit it out through the while loop. Rinse and repeat until done.
edit
I see you put your open tablerow statement in the foreach but close it outside. So either you want it all printed on one line or is it an error? If its on one line, make sure you open the table row BEFORE the while loop and end it AFTER, else it's like how i spit it out.
I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
I'm trying out my hand at php at the moment - I'm very new to it!
I was wondering how you would go about selecting all items from a mySQL table (Using a SELECT * FROM .... query) to put all data into an array but then not displaying the data in a table form. Instead, using the extracted data in different areas of a web page.
For example:
I would like the name, DOB and favorite fruit to appear in one area where there is already say 'SAINSBURYS' section hardcoded into the page. Then further down the next row that is applicable to 'ASDA' to appear below that.
I searched both here and google and cant seem to find an answer to my strange questions! Would this involve running the query multiple times filtering out the sainsburies data and the asda data where ever I wanted to place the relevant
echo $row['name']." ";
echo $row['DOB']." "; etc etc
next to where it should go?
I have got php to include data into an array (I think?!)
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['DOB']." ";
echo $row['Fruit']." ";
}
?>
Just place this (or whatever your trying to display):
echo $row['name']." ";
Anywhere you want the info to appear. You can place it within HTML if you want, just open new php tags.
<h1>This is a the name <?php echo $row['name']." ";?></h1>
If you want to access your data later outside the while-loop, you have to store it elsewhere.
You could for example create a class + array and store the data in there.
class User {
public $name, $DOB, $Fruit;
}
$users = new array();
$query = "SELECT * FROM people";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$user = new User;
$user->name = $row["name"];
$user->DOB = $row["DOB"];
$user->Fruit = $row["Fruit"];
$users[$row["name"]] = $user;
}
Now you can access the user-data this way:
$users["USERNAME"]->name
$users["USERNAME"]->DOB
$users["USERNAME"]->Fruit