Error when using while loop in another while loop - php

I was trying to do a stock recording function which post out product in rows using while loop and the stock count in another while loop but when i run the code it returns error in the second while loop and i'm not sure which part did i went wrong. Need some help here!
Here's the code:
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('EmployeeDB');
$rproduct = "SELECT Product FROM `tbl_user` GROUP BY Product";
$result = mysql_query($rproduct);
while($row1 = mysql_fetch_array($result)){
$prod = $row1['Product'];
echo "<tr><th>$prod</th>";
$rstock = mysql_query('SELECT opening, closing FROM tbl_user WHERE Product = $prod ORDER BY date');
while ($row2 = mysql_fetch_array($rstock)) {
echo "<td>".$row2['opening']."</td>";
echo "<td>".$row2['closing']."</td>";
}
echo"</tr>";
}

Quick solution
Replace this line:
$rstock = mysql_query('SELECT opening, closing FROM tbl_user WHERE Product = $prod ORDER BY date');
With:
$rstock = mysql_query("SELECT opening, closing FROM tbl_user WHERE Product = '$prod' ORDER BY date");
There are two problems with the original line:
You were using a variable inside a single quoted string and that is wrong, it only works with double quoted strings.
the variable $prod needs to be wrapped in single quotes because you are searching for a string, without the quote you were actually telling mysql to search for a row where column product equals the value inside a column which name is whatever inside variabe $prod.
Better solution
Use mysqli or pdo instead of mysql because it is deprecated, and prepare statements instead of just putting variables inside strings.

Related

PHP/SQL Trying to get all order numbers where status = something and put order number into array

I'm working on a Kitchen Display Screen. I have it working if I know the order numbers. I'm trying to get all of the order numbers where status = "INQUEUE" and put those numbers into an array. The goal is to have a count of the total "INQUEUE" orders as well as have the segments on the screen only show arr[0]-Arr[4]. For some reason this section of code causes an error.
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus=$status";
$result = mysql_query($sql) or die(mysql_error());
while( $row = mysql_fetch_assoc( $result ) ) {
$arr[] = $row[ORDID];
}
I'm hoping to grab all of the order numbers that have a status of "INQUEUE" into the array, so I can display the orders as arr[X]
What is the specific error you are receiving?
One thing that stands out on the query is the variable needs to be enclosed within single quotes so it looks like this:
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
Sometimes when I'm working with dynamically-built queries I like to echo out the query string so I can see exactly how it's being sent to the server.
Also, it's always a good idea to get in the habit of using prepared statements with parameterized queries when working with dynamically-built SQL queries.
Also, in agreement with ArtisticPhoenix, I recommend porting over to another library. Finally, make sure the array index descriptor is enclosed in double quotes. Here's your code using mysqli:
$link = mysqli_connect("dbserver", "user", "password", "database");
$status= "INQUEUE";
$arr = array();
$sql = "select ORDID from HEADERS where CurrentStatus='$status'";
$result = mysqli_query($link, $sql);
while( $row = mysqli_fetch_assoc($result)) {
$arr[] = $row["ORDID"];
}

Display data from table with specific column values via php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
this ought to be simple but am yet to find an answer for it (i have searched the questions in stackoverflow). am on php and i have a table books on mysql.
What i want is a list displayed in my webpage with these specifics on a table created by php. I know the mysql code:
SELECT title FROM books WHERE category='currently reading'
applying that on php has brought this error, Parse error: syntax error, unexpected 'currently' (T_STRING)
Here is my php code:
<?php
include('include/databaseconnection.php');
include('include/insertingbooks.php');
// selecting data
$result = mysql_query ('SELECT title FROM books WHERE category='currently reading'';);
//("SELECT title FROM books WHERE category LIKE $currently");
//opening table tag
echo "<table border = 1px>";
while ($data = mysql_fetch_array($result)) {
// printing table row
echo'<tr>';
echo '<td>'.$data['title'].'</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
?>
If i decide to leave out WHERE clause, it works perfectly except it displays all the books.
The options i have tried already
using WHERE category LIKE $category while setting up a variable $category = "currently reading"; but it dint work.
trying to link it to the form i got the the values of category from by adding include('include/insertingbooks.php'); (which contains $category =$_POST ['category'];) and trying to put $category.
using WHERE not but it didnt work at all.
You have bad quotes and an extra semi-colon here -
$result = mysql_query ('SELECT title FROM books WHERE category='currently reading'';);
Change to this (note the double quotes) -
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'");
In addition, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and use PDO.
You should also add MySQL error checking to your queries and connections.
Using or die(mysql_error()) to mysql_query().
For example:
$result = mysql_query ("SELECT title
FROM books
WHERE category='currently reading'")
or die(mysql_error());
Which would have caught and displayed the syntax error.
there is only quotes problem
Please replace your query to:
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'";);
Please note you can not use same quotes eg. If you are using double quotes then use single quotes inside and if single quotes then double code inside
Use this code:
<?php
include('include/databaseconnection.php');
include('include/insertingbooks.php');
// selecting data
$result = mysql_query ("SELECT title FROM books WHERE category='currently reading'");
//("SELECT title FROM books WHERE category LIKE $currently");
//opening table tag
echo "<table border = 1px>";
while ($data = mysql_fetch_array($result)) {
// printing table row
echo'<tr>';
echo '<td>'.$data['title'].'</td>';
echo'</tr>'; // closing table row
}
echo '</table>';
?>

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

PHP: replace a "variable" from mysql query (Table's content)

I am trying to echo a variable, from a mysql query, like this:
<?php
...//FYI: mysql connection already established
//Table: title
//col: page | title
//row: html | "$domain_name: Welcome"
$page_id = basename(getcwd());
$domain_name = "Name of My Domain";
$sql = "SELECT title FROM mydatabase.title WHERE page = '$page_id' ";
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];
//it outputs: $domain_name: Welcome", instead of "Name of My Domain: Welcome"
?>
What am I doing wrong?
I am trying to replace the "variable [$domain_name] in the table's content for it's php value. -I thought " (double quotes) are supposed to replace the variable with it's value.
PS. I am a beginner
EDIT 2/7/2012, 3:14pm: Forgot to mention. The query works OK. $dba['title'] has "$domain_name: Welcome" as a value. The problem is, it is not replacing $domain_name
I thought " (double quotes) are supposed to replace the variable with it's value.
That works only in case when you specify the string in your code. If the string comes from outside - it doesn't have such magic behaviour.
So the only solution you could go with is:
echo str_replace('$domain_name', $domain_name, $dba["title"]);
Or you could go with some sort of template engine like Twig or Smarty and treat your database value as a template, and your variables as the data.
You can replace it on database level:
$sql = 'SELECT REPLACE(title, \'$domain_name\',\''.$domain_name.'\') as title FROM mydatabase.title WHERE page = '.intval($page_id);
//The query's result is 1 row
$dbq = mysql_query ($sql);
$dba = mysql_fetch_array( $dbq );
echo $dba["title"];
(Note the single quotes)

Categories