I have the following code snippet that is working find but am trying to sort the results ASC. I've tried numerous variations and none work?
$res = mysql_query('SELECT DISTINCT call FROM ' . DB_TABLE);
Does not work:
$res = mysql_query('SELECT DISTINCT call FROM ' . DB_TABLE . 'ORDER BY call ASC');
This should work:
$res = mysql_query('SELECT DISTINCT call FROM ' . DB_TABLE . ' ORDER BY call ASC');
Note the space before ORDER
You miss a space :
$res = mysql_query('SELECT DISTINCT call FROM ' . DB_TABLE . ' ORDER BY call ASC');
Try using the backtick (`) operator with your mysql query.
$res = mysql_query('SELECT DISTINCT `call` FROM ' . DB_TABLE . ' ORDER BY `call` ASC');
And all should work well.
Related
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 1 year ago.
I looked for an answer but could not find it as the issue seems to be slightly different here.
$vid = $_SESSION['ID_Vendor'];
echo "ID: $vid";
$q = 'SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor=res.ID_Vendor AND res.ID_Vendor="$vid" ORDER BY business_name ASC';
The variable $vid has indeed a value (equal to 2 in this case, but it could be different), HOWEVER, when I specifically set
WHERE res.ID_Vendor=2
my query returns the correct and expected list of values, but when, instead, I use
WHERE res.ID_Vendor="$vid"
with "$vid", the echo of my values is simply empty.
Below is the full snippet of the code to also echo the output.
Thanks for your help.
$vid = $_SESSION['ID_Vendor'];
echo "ID: $vid";
$q = 'SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor=sfe.ID_Vendor AND res.ID_Vendor="$vid" ORDER BY business_name ASC';
$r = mysqli_query($connection, $q);
while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) {
echo '>' . htmlspecialchars($row[0]) . ' ' . htmlspecialchars($row[1]) . ' ' . htmlspecialchars($row[2]) .'</option>';
}
PHP does not recognize variable in apostrophes pair ''. Put your variable in "". EG:
"WHERE res.ID_Vendor='$vid'"
Since I raised the idea, I suppose I should illustrate the use of prepared statements.
Using mysqli one would proceed as follows (assuming $connection has been successfully initialized):
// The indentation here is purely a matter of personal preference
$query = 'SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor = res.ID_Vendor
WHERE res.ID_Vendor = ?
ORDER BY business_name ASC';
$stmt = $connection->prepare($query);
$stmt->bind_param('s', $vid); // 's' assumes $vid is string; use 'i' for int
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_array(MYSQLI_NUM))
{
echo '>' . htmlspecialchars($row[0]) . ' ' . htmlspecialchars($row[1]) . ' ' . htmlspecialchars($row[2]) .'</option>';
}
The idiom is the same using PDO. The format of the PDO data source name (DSN) is documented online.
$conn = new PDO($dsn, $username, $password); // define these vars elsewhere
$query = 'SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor = res.ID_Vendor
WHERE res.ID_Vendor = :vid
ORDER BY business_name ASC';
$stmt = $conn->prepare($query);
$stmt->execute(array(':vid' => $vid));
while ($row = $stmt->fetch(PDO::FETCH_NUM))
{
echo '>' . htmlspecialchars($row[0]) . ' ' . htmlspecialchars($row[1]) . ' ' . htmlspecialchars($row[2]) .'</option>';
}
In both cases I leave error handling as an exercise for the reader.
There's a few problems with your code:
Firstly, this won't work and will echo $vid literally.
echo "ID: $vid";
This will return: ID: $vid
You'll need to concat the string with the variable, it should be:
echo "ID: " . $vid;
This will return: ID: 2
Secondly, your query won't work:
$q = 'SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor=res.ID_Vendor AND res.ID_Vendor="$vid" ORDER BY business_name ASC';
You should enclose the query with double quotes and your variable with single quotes instead:
$q = "SELECT business_name, vd.ID_Vendor, res.ID_RestaurantEstablishment
FROM restaurant res
INNER JOIN vendor_data vd
ON vd.ID_Vendor=res.ID_Vendor AND res.ID_Vendor='$vid' ORDER BY business_name ASC";
For SQL, not like javascript or php, only single quote is allowed for string or char.
For MySQL, if the column type of res.id_vendor is number, res.id_vendor='1' is the same as res.id_vendor=1, so it is better always wrap the variable with single quote, as in res.id_vendor='$vid'
Lastly, comments on coding conventions: it is recommended to not mix upper case and lower case characters in column naming, use "_" as word delimiters, like
vd.id_vendor
res.id_restaurant_establishment
I have some code which generates a MySQL query string called $query:
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
$clue = $_POST['postcode'];
$onwhat="Postcode";
$query .= $onwhat . " like '%$clue%') order by id desc";
$result = mysql_query($query, $connection) or die(mysql_error());
This returns something like:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which works fine. I've then altered the code because I want to search on more fields so it now reads:
$remap = array("Postcode", "Street", "HouseNum", "District", "Town");
$query = "select * from Surveys where surveylayoutid='$surveyid' and customerid='" . $_SESSION['login_customerid'] . "' and (";
for ($i=0; $i<=4; $i++) {
if ($_POST[strtolower($remap[$i])]!="") {
$clue = $_POST[strtolower($remap[$i])];
$query .= $remap[$i] . " like '%$clue%') order by id desc";
break;
}
}
This also returns:
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%dn%') order by id desc
which on the face of it is identical but it generates this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'like '%dn%' order by id desc' at line 1
In both cases $query contains the same "text" but for some reason isn't treated as a valid MySQL query in the updated code, can anyone tell me why?
One possible problem could be the interpretation of the content here.
If you use:
$query .= $remap[$i] . " like '%$clue%') order by id desc";
All that is inside "" gets to be interpreted. Thus there could be unwanted side effects that you don't see at first glance and can explain what is happening. To avoid this it would have to be changed to:
$query .= $remap[$i] . ' like ' . "'" . '%' . $clue . '%' . "') order by id desc";
Even though more clunky in terms of how big it is, it makes sure that $lue and also the % are not interpreted as all in between ' ' is not interpreted.
See if this help you solve your problem?
$remap = array(
"Postcode",
"Street",
"HouseNum",
"District",
"Town"
);
for ($i = 0; $i <= 4; $i++)
{
if ($_POST[strtolower($remap[$i]) ] != "")
{
$query = "select * from Surveys where surveylayoutid='12' and customerid='1' and (";
$clue = $_POST[strtolower($remap[$i]) ];
$query.= $remap[$i] . " like '%$clue%') order by id desc";
$query_done[] = $query;
unset($query);
$result = mysql_query($query_done[$i], $connection) or die(mysql_error());
// Display your result here
}
}
I tried changing your code abit, and it seems the result is something like this
select * from Surveys where surveylayoutid='12' and customerid='1' and (Postcode like '%Postcode%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Street like '%Street%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (HouseNum like '%HouseNum%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (District like '%District%') order by id descselect * from Surveys where surveylayoutid='12' and customerid='1' and (Town like '%Town%') order by id desc
I am generating the first part of the query like this:
while ($all_products = $db->fetch_array($all_prods))
{
$filter_string .= 'AND product_id !=';
$filter_string .= $all_products['item_id'];
$filter_string .= ' ';
}
and then the second part like this:
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
However it's giving me a mySQL syntax error and the $filter_string part strangely adds ' twice before and after the string, so it runs like this:
WHERE user_id='12345' AND active=1 'AND product_id !=0001 AND product_id !=0002 ' ORDER BY RAND ...
What am I doing wrong?
$filter_string adds ' because you put it there. :P
Try with just the double quotes around $filter_string:
$sql_more_items = $db->query("SELECT * FROM db_products WHERE owner_id='" . $user_id . "' AND active=1 " . $filter_string . "ORDER BY RAND() LIMIT 10");
$sql_more_items = $db->query("SELECT * FROM db_products
WHERE owner_id='" . $user_id . "' AND active=1 '" . $filter_string . "'
ORDER BY RAND() LIMIT 10");
Check the way you're performing a string concatenation (putting together strings). It seems like there's a copy/paste error as you're using '" instead of just a "
I would use whitespace (and a good code editor) to your advantage by reformatting your code to look like this:
$queryString = "SELECT * FROM db_products WHERE owner_id='$user_id'"
." AND active=1 " //Note these
. $filter_string //are separated
. "ORDER BY RAND() LIMIT 10 "; //into individual lines
$sql_more_items = $db->query($queryString);
This style helps you keep track of whether you're using " or ' for your strings and also helps you debug things more easily than putting it into one giant hard to read string.
That's probably because of the part
`"' AND active=1 '"`
^.... This ' here
My code loads with the following text on top of it:
"Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5"
Could someone help me find a solution?
Thanks
//jQuery
var value = '3';
$.post("load.php", {number: value} ,function(data){
$('p').append(data);
});
$('p').load('load.php');
//PHP load.php
//I have the escape inside $db.
$random = $_POST['number'];
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
$result = $db->get();
foreach ($result as $key => $value){
echo $value['user'];
};
//Output
Problem with SQL: SELECT * FROM table WHERE id < ORDER BY id DESC LIMIT 5
$value['user']
Try changing it to this one:
$db->query("SELECT * FROM table WHERE id < " . $random . " ORDER BY id DESC LIMIT 1");
Better use double instead of single quotes.
The reason this is not working is because single quotes does not allow PHP to expand the variable value.
So instead of this:
$db->query('SELECT * FROM table WHERE id <' . '$random' . 'ORDER BY id DESC LIMIT 1');
You might do this:
$db->query('SELECT * FROM table WHERE id <' . $random . ' ORDER BY id DESC LIMIT 1');
Just remove the quotes in $random and you'll be well.
I need to have my results sorted by "ORDER BY prod_name" in my SQL statement but I cannot figure out get it to work. I tried after
$thisProduct .= " AND prod_type = 1 ORDER BY prod_name";
and also after
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "' ORDER BY prod_name";
But I cannot get my results to sort correctly. Am I placing the order by in the wrong spot or did I query the DB incorrectly?
Thank you in Advance, I am still pretty new at MYSQL queries.
$thisProduct = "SELECT prod_name AS Name, days_span, CONCAT(LEFT(prodID,2),ID) AS ID, geo_targeting FROM products WHERE status = 'Active' AND vendID = ".$resort['vendID'];
if (isset($_GET['product']) AND is_numeric($_GET['product'])) {
$thisProduct .= " AND ID = '" . mysql_real_escape_string($_GET['product']) . "'";
}
else {
$thisProduct .= " AND prod_type = 1";
}
$thisProduct .= " LIMIT 1";
$getThisProduct = mysql_query($thisProduct);
if (!$getThisProduct/* OR mysql_num_rows($getThisProduct) == 0 */) {
header("HTTP/1.0 404 Not Found");
require APP_PATH . '/404.html';
die();
}
$thisProductData = mysql_fetch_assoc($getThisProduct);
You should have:
$thisProduct .= " ORDER BY prod_name";
$thisProduct .= " LIMIT 1";
(Note that the LIMIT 1 means you only get one record).
Assuming that your query is correct and you want the first product by name:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
I believe it should go right before your "LIMIT 1", as in:
$thisProduct .= " ORDER BY prod_name LIMIT 1";
Insert it before the LIMIT
$thisProduct .= " ORDER BY prod_name LIMIT 1";
You can the select syntax at http://dev.mysql.com/doc/refman/5.0/en/select.html
SELECT query usually takes following form
SELECT which_all_to_select
FROM which_table/tables
WHERE criteria
ORDER BY column_name ASC/DESC;
ASC ascending order, and DESC is descending order
This orders query results by column_name specified in ORDER BY clause .