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>';
?>
Related
I'm trying to get all records from db using getRows method, to achieve that I need to implode special characters.
In previous function, to get $ids I used:
foreach ($ids as &$id) $id = (int)$id;
$rows = $this->db->getRows('SELECT name, id FROM database WHERE id IN ('.implode(',', $ids).')');
if (count($rows)) {
foreach ($rows as $row)
{
$ret[$row['id']] = $row['name'];
}
}
but in my next function I need to use name to search for records.
Because name is in single quotes 'name' I tried making it like this:
foreach ($names as $name) $id=(int)$name;
$rows = $this->db->getRows('SELECT name, is_active FROM database WHERE name IN ('.implode(',',$names).')');
if(count($rows))
{
foreach ($rows as $row)
{
$ret[$row['name']] = $row['is_active'];
}
}
it doesnt solve the problem, it just crashes. So I tried changing it a bit with separating it with double quotes:
$rows = $this->db->getRows("SELECT name, is_active FROM database WHERE name IN (" .implode(',',$names) .")");
still getting same error database query error.
and I dont know really what to do next. I believe I cant pass that many quotes inside of a implode.
Query should look like this: SELECT name, is_active FROM database WHERE name IN ('name1', 'name2', 'name3')
I tried to follow PHP: implode - Manual with same error results.
Switching between single or double quotes like you did, doesn't change the fact that you did not add any quotes around the individual name values at all. These quotes are the string delimiters the PHP syntax requires, but you have not added any quotes around the names in your implode yet, which the SQL syntax requires.
And implode only inserts the separator between the values - so the quote character before the first, and the quote character after the last item, still need to be added.
You want something like
'SELECT name, is_active FROM database WHERE name IN ("'.implode('","',$names).'")'
which will produce
SELECT name, is_active FROM database WHERE name IN ("a","b","c")
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.
I have the following code:
$indtag = '';
foreach($pretag as &$indtag) { //cycles through tags, puts quotes into check by tag
$quote = mysqli_query($mysqli, "SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'");
while($row = mysqli_fetch_assoc($quote)) {
echo $row['$indtag'];
echo $row['id'];
}
}
The table has fields for ids, quotes, then an individual column for each tag (ang for anger being an example). pretag is an array full of tags (rom is romance, ang is anger, dece is deception) that I'm running through, trying to find quotes with those IDs and tags. The statement works fine in SQL when I run it with ang, it selects the IDs fine, but when I try to select the column/field for a tag using a variable, nothing comes back. Any ideas?
You're using the variable $indtag where you should be using the column name indtag:
SELECT `id`, `$indtag` FROM `beyonce` WHERE `$indtag` LIKE '%$indtag%'
^ ^
And as #tadman points outs, don't do it this way, use mysqli_stmt_bind_param with a prepared statement or you are in for a wild ride.
This line in your code doesn't need quotes.
echo $row['$indtag']; // Won't work
echo $row[$indtag]; // Will work
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"];
}
I have an existing recordset that retrieves all the information from a table in mysql called $rrows. What I am hoping to do is to use this existing recordset within a new mysql query.
For example I have the following line that retrieves the "product code" from one table:
<?php echo $rrows['productcode']; ?>
I am trying to then gather the respective images from a new table using this productcode by something similar to:
<img src="<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnimages WHERE productcode='$rrows['productcode']'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>">
Can this be done? Originally I was going to LINK tables together to get all the information, but this doesnt work as some of the product codes in the main do not have corresponding data in the 'furnimages' table.....
Thanks in advance!
JD
sprintf() is your best friend here.
$sql = <<<sql
SELECT * FROM furnimages
WHERE productcode=%d
sql;
$result = mysql_query(sprintf($sql, $rrows['productcode']));
So, %d is the placeholder in the string to swap in the second argument in the call to sprintf();
%d denotes an integer placeholder; if $rrows['productcode'] is a string, use %s.
This is better than simply quoting value of the variable as it adds a type constraint which reduces the risk of nasty sql injection.
It also makes it eminently more readable.
Check out the PHP Data Objects extension, though, because that really is the only way forward for this type of thing.