Mysql SELECT with WHERE clause not working with variable - php

I am pulling my hair out. I have two SELECT statements that are basically the same principal. The first one is working and the second one will not work with the WHERE clause in it. I need some fresh eyes and suggestions. I have been on every forum and read every post and have tried many "solutions" to no avail. Hoping someone will see something I have missed.
$oID = zen_db_prepare_input($_GET['oID']);
// Color coding for invoice -Start queries---
$query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
$result = $db->Execute($query);
$shiploc = $result->fields['shipping_method'];
if ($result->RecordCount() > 0) {
echo 'Test Query: = ' . $result->fields['shipping_method'];
} else {
echo 'Sorry, no record found for product number ' ;
}
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= $shiploc";
$results = $db->Execute($sql);
$newcolorblock = $results->fields['color_code'];
if ($results->RecordCount() > 0) {
echo 'Color Query: = ' . $results->fields['color_code'];
echo 'Location: = '. $results->fields['pickup_name'];
} else {
echo 'Sorry, no record found for Color Code ' ;
}
Thank you in advance for your help and suggestions hopefully you will be able to see something I can't.
First query results: Test Query: = Store Pickup (Mooresville - Gold's Gym)
Second query results: WARNING: An Error occurred, please refresh the page and try again.
If the WHERE clause is removed it returns values but not the correct ones. I need the WHERE statement for it to pull the correct information.
ANSWER kindly provided by bloodyKnuckles :)
$sql= "SELECT * FROM cart1_store_locations WHERE pickup_name= $shiploc";
changed to: (Needed to be escaped to comp for 's in the table data)
$shiploc_escaped = mysql_escape_string($shiploc);
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc_escaped."'";
I have not used this forum before. LOVE IT!!! Thank you everyone!

Since your string has a single quote in it:
Store Pickup (Mooresville - Gold's Gym)
...you need to escape the variable $shiploc:
$shiploc_escaped = addslashes($shiploc);
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc_escaped."'";
Reading up on Zen Cart Escaping Content, it appears this is an option:
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$db->prepare_input($shiploc)."'";
...and, better yet, this:
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= :pickup_name:";
$sql = $db->bindVars($sql, ':pickup_name:', $shiploc, 'string');

Your $shiploc might be null. Before second query please write var_dump($shiploc); and let us know what you get.
EDIT
$oID = zen_db_prepare_input($_GET['oID']);
// Color coding for invoice -Start queries---
$query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
$result = $db->Execute($query);
$shiploc = $result->fields['shipping_method'];
if ($result->RecordCount() > 0) {
echo 'Test Query: = ' . $result->fields['shipping_method'];
} else {
echo 'Sorry, no record found for product number ' ;
}
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc."'";
$results = $db->Execute($sql);
$newcolorblock = $results->fields['color_code'];
if ($results->RecordCount() > 0) {
echo 'Color Query: = ' . $results->fields['color_code'];
echo 'Location: = '. $results->fields['pickup_name'];
} else {
echo 'Sorry, no record found for Color Code ' ;
}

Related

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

PHP and MySQL query - multiple criteria

I'm having a problem with the code listed below where I'm running a query on a database based on search criteria the user may have selected on a form.
At the moment, querying the database just on the author's name works fine. But if I uncomment the rest of the if-else statements, none of the queries work. I just get a blank table back with no results returned.
I've tried each if/else statement individually with the others commented out and they all work fine on their own, but not when they're all uncommented.
Can anyone point me in the right direction?
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if ($_POST['author'])
$query .= " AND '$author' = author";
/*
else if ($_POST['author'] AND $_POST['year'])
$query .= " AND '$author' = author AND '$year' = year";
*/
/*
else if ($_POST['cover_art']) {
$query .= " AND '$cover_art' = cover_art";
}
*/
/*
else if ($_POST['interior_art']) {
$query .= " AND '$cover_art' = cover_art";
}
else {
// do something else
}
*/
Check this solution:
$author='Bred';
$year='2012';
$cover_art='';
$queryA=array();
if ($author<>'') $queryA []= "'$author' = author";
if ($year<>'') $queryA []= "'$year' = year";
if ($cover_art<>'') $queryA []= "'$cover_art' = cover_art";
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if(count($queryA)>0) $query.=' AND '.implode(' AND ',$queryA);
echo $query;

mysql query works with plain text, but not with variable

I am trying to print out some topic information, but it is not going so well. This is my query:
SELECT * FROM topics WHERE id='$read'
This doesn't work. I've echo'ed the $read variable, it says 1. So then if I do like this:
SELECT * FROM topics WHERE id='1'
It works perfectly. I don't get what is the problem. There's no hidden characters in $read or anything else like that.
Try like this:
$query = "SELECT * FROM topics WHERE id='" . $read . "'"
ID is normally a numeric field, it should be
$id = 1;
$query = "SELECT * FROM topics1 WHERE id = {id}"
If you are using strings for some reason, fire a query like
$id = '1';
$query = "SELECT * FROM topics1 WHERE id = '{$id}'"
SELECT * FROM topics WHERE id=$read
it consider it as string if you put i single quotes
I wonder why all the participants didn't read the question that clearly says that query with quotes
SELECT * FROM topics WHERE id='1'
works all right.
As for the question itself, it's likely some typo. Probably in some other code, not directly connected to $read variable
try
$query = sprintf("SELECT * FROM topics WHERE id='%s';",$read);
Also remember to escape the variable if needed.
Looks like you might have an issue with the query generation as everyone else is pointing to as well. As Akash pointed out it's always good to build your query in to a string first and then feed that string to the MySQL API. This gives you easy access to handy debugging techniques. If you are still having problems try this.
$id = 1;
$query = "SELECT * FROM `topics1` WHERE `id`={$id}";
echo ": Attempting Query -> {$query}<br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The query failed!<br />" . mysql_error($dblink) . "<br />");
$cnt = mysql_num_rows($res);
if($cnt <= 0)
{
$query = "SELECT `id` FROM `topics1`";
echo "No records where found? Make sure this id exists...<br />{$query}<br /><br />";
$res = mysql_query($query, $dblink);
if($res <= 0)
die("The id listing query failed!<br />" . mysql_error($dblink) . "<br />");
while($row = mysql_fetch_assoc($res))
echo "ID: " . $row['id'] . "<br />";
}
This will at least let you monitor between calls, see what your query actually looks like, what mysql says about it and if all else fails make sure that the ID you are looking for actually exists.
try with this : SELECT * FROM topics WHERE id=$read

max(id) and limit 10, but use them in different places

I have two tables, posts and sections. I want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places. I make a function:
function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
$maxpost12 =mysql_query($maxpost1);
while ($maxpost_rows = mysql_fetch_array($maxpost12 ,MYSQL_BOTH)){
$maxpost2 = $maxpost_rows[0];
}
$query = "SELECT * FROM posts WHERE id = $maxpost2";
$query2 = mysql_query($query);
return $query2;
}
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){
echo $rows['title'] . "<br/>" . "<br/>";
echo $rows['id'] . "<br/>" . "<br/>";
echo $rows['image_section'] . "<br/>";
echo $rows['subject'] . "<br/>";
echo $rows['image_post'] . "<br/>";
}
How can it take these ten results but use them in different places, and keep them arranged from one to ten.
this was the old case and i solve it but i found another problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.
function getmax_id_with_minus ($minus){
mysql_set_charset('utf8');
$maxid ="SELECT max(id) FROM posts";
$maxid1 =mysql_query($maxid);
while ($maxid_row = mysql_fetch_array($maxid1)){
$maxid_id = $maxid_row['0'];
$maxid_minus = $maxid_id - $minus;
}
$selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
$query_selectedpost =mysql_query($selectedpost1);
return ($query_selectedpost);
}
<?php
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>
anyway "really" thanks again :) !
A few thoughts regarding posted code:
First and foremost, you should stop using mysql_ functions as they are being deprecated and are vulnerable to SQL injection.
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 20";
When you SELECT MAX, MIN, COUNT, AVG ... functions that only return a single row, you do not need an ORDER BY or a LIMIT.
Given that you are only asking for the MAX(id), you can save work by combining your queries like so:
SELECT * FROM posts
WHERE id = (SELECT MAX(id) from posts WHERE section_id = $section_id)
If I'm understanding what you're trying to do (please correct me if I'm wrong), your function would look something like:
function sectionposts($section_id) {
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$stmt = mysqli_prepare($link, "SELECT title, id, image_section, subject, image_post FROM posts "
. "WHERE section_id = ? ORDER BY id DESC LIMIT 10");
mysqli_stmt_bind_param($stmt, $section_id);
return mysqli_query($link, $stmt)
}
$result = sectionposts(6);
while ($row = mysqli_fetch_assoc($result)) {
echo $rows['title'] . "<br /><br />";
echo $rows['id'] . "<br /><br />";
echo $rows['image_section'] . "<br />";
echo $rows['subject'] . "<br />";
echo $rows['image_post'] . "<br />";
}
Try this instead, to save yourself a lot of pointless code:
$sql = "SELECT * FROM posts WHERE section_id=$section_id HAVING bar=MAX(bar);"
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo ...;
echo ...;
The having clause lets you find the max record in a single operation, without the inherent raciness of your two-query version. And unless you allow multiple records with the same IDs to pollute your tables, removing the while() loops also makes things far more legible.
Seems like you want to store them in an array.
$posts = array(); //put this before the while loop.
$posts[] = $row; //put this in the while loop

The Select query I am using is not working.. Can Somebody Guide me to the Correct way?

I am using the Select query as
SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'
Here I need all the records whose ordering is less than 1 of the selected record's order($rec['ordering'] = getting from other select query ) when I am trying to echo the query I am not getting complete statement but getting only this -1' AND parent = '0'
here is the whole snippet
$where = ' WHERE (id = ' . implode( ' OR id = ', $cid ) . ')';//Pranav Dave Coded
echo $selquery = "SELECT id, ordering FROM `jos_menu`".$where; //Pranav Dave Coded
$db->setQuery( $selquery );//Pranav Dave Coded
$record = $db->loadAssocList(); //Pranav Dave Coded
if ($model->orderItem($id, -1)) {
echo "<pre>";
print_r($model);
/*exit;*/
//echo $updorderup = mysql_escape_string($model->_db->_sql);//Pranav Dave Coded
foreach($record as $rec)//Pranav Dave Coded
{
echo $aboverow = "SELECT id, ordering FROM `jos_menu` WHERE ordering='".$rec['ordering'] -'1' ."' AND parent = '0'";
$db->setQuery( $aboverow );
$above = $db->loadAssoc();
echo "<pre>";
print_r($above);
}//end of foreach
}//end of if
Please suggest me where I am getting wrong.....
It looks like you may need to unwrap the -1 from the quotes:
WHERE ordering='".($rec['ordering'] - 1)."' AND parent = '0'";
Why do you trying to put everything inline?
Why not to make some preparations first?
Why not to compare resulting query with sample one?
Why don't you check every step if it return proper result?
$val = $rec['ordering'] - 1;
//let's see if $cal has proper value:
echo $val."<br>";
$sql = "SELECT id, ordering FROM `jos_menu` WHERE ordering = $val AND parent = 0";
//let's see if query looks good:
echo $sql;
//let's print sampe query to compare:
echo "<br>" ;
echo "SELECT id, ordering FROM `jos_menu` WHERE ordering = 1 AND parent = 0";
As Daniel said, you need to remove the quotes around the -1. Currently its trying to minus a string, which it wouldn't be happy with at all ;)

Categories