jQuery and php. mysql error - php

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.

Related

MySQL syntax error in string built by PHP

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

Printing table values in ascending order

I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ

Random Picture From Database MYSQL

Hi trying to grab 7 random photos from my database where type='img'
Some code
<?php
$ilosc= 7;
$Query='SELECT * FROM tentego_img WHERE type = 'img' ORDER BY RAND() LIMIT '.$ilosc;
$QueryResult=mysql_query($Query);
while($Kol=mysql_fetch_array($QueryResult)){
echo('<td style="border: 0px"><img src="/upload/'.$Kol['src'].'" alt="'.$Kol['title'].'" title="'.$Kol['title'].'" width="120px" height="120px" /></td> ');
}
?>
So should catch 7 randoms photos where type= img, but have no idea whats wrong with code
when query looks like `
$Query='SELECT * FROM tentego_img ORDER BY RAND() LIMIT '.$ilosc;`
works fine but i need to show just photos where type=img
Help Please
Cheers
Use different characters:
$Query="SELECT * FROM tentego_img " .
"WHERE type='img' ORDER BY RAND() LIMIT ".$ilosc;
or escape the single quotes:
$Query='SELECT * FROM tentego_img ' .
'WHERE type=\'img\' ORDER BY RAND() LIMIT '.$ilosc;
You must escape your ' characters or use " around the string
$Query = "SELECT * FROM tentego_img WHERE type = 'img' ".
"ORDER BY RAND() LIMIT ".$ilosc;

MySQL - Select differently

I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.
Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id

Where do I insert the ORDER BY in my MYSQL query

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 .

Categories