I am a newbie in MySQL and PHP. I have a HTML form where I would like to pass 1 variable from to my PHP code and then run a query on my database for the record that holds that variable under the column 'Serial'. I can run it fine when I hard code the 'serial' that I want to look up but when I try with the variable I get an error.
Any help would greatly be appreciated! Or a better way to do this.
Here is my error: Unknown column 'amg002' in 'where clause'
Here is my code;
$serial= $_POST['Serial'];
echo $serial;
//Connect To Database
$link = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
echo "Connected to MySQL<br />";
//Select the database - 'SiteInfo'
// Collects data from "SiteInfo" table
//****This is where I am running into the error***
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial;
// This works!!!
//$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ="amg002";';
$data = mysql_query($sql)
or die(mysql_error());
// puts the "SiteInfo" info into the $info array
$info = mysql_fetch_array( $data );
//Print out the contents of the entry
echo "Site Name: ".$info['SiteName'] . "<br /";
Print "Serial Number: ".$info['Serial'] . "<br />";
Print "Location: ".$info['Location'] . "<br />";
// Close the database connection
mysql_close($link);
echo "Connection Closed. <br />";
I agree its a quote issue, but here is how my code would look.
$sql = 'SELECT * FROM SiteInfo WHERE Serial = "' . $serial . '"';
or
$sql = "SELECT * FROM 'SiteInfo; WHERE 'Serial' = \"$serial\"";
Looks like a quote issue:
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial.';
should be
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` ='".$serial."'";
It means your variable:
$_POST['Serial']
is coming empty. You need to run your code if it isn't empty by checking it via isset like this:
if (isset( $_POST['Serial'])) {
$serial= $_POST['Serial'];
// your rest of the code
}
Also if Serial is string and not a number, you need to put it in quotes, use below query:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
You can also check out what does your query come up like:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
echo $sql;
exit;
Related
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 ' ;
}
I have a SQL query in my PHP file that makes use of some variables in it. I want to print the query itself on the localhost to check as to whether the entire query is been executed or not.
My query is like this:
$result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%',$db);
I am trying to print the query using echo $result but get Resource id #25 on localhost. I want to print Select * FROM ... as the output. Is there any way?
First of all: You are missing a double quote: $result = mysql_query("SELECT * FROM sample WHERE col01 LIKE '%$abc%'",$db).
That said, what stops you from
$sql="SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql,$db);
echo $sql;
If you were using PDO (and you should, the old mysql_ functions are deprecated and insecure) you could just use PDOStatement->queryString property to view the query at a later time.
Store as a variable $sql
Its normal, first you need to fetch that resource obj
And anyway you missing a double quote,
example.
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
$result = mysql_query($sql);
while ($line = mysql_fetch_object($result)) {
echo $line->colname ."\n";
}
echo "\n" . ' query: ' . $sql
And from PHP 5.5.0 and beyond use mysqli
$sql = "SELECT * FROM sample WHERE col01 LIKE '%$abc%'";
if ($result = $mysqliobj->query($sql)) {
while($line= $result->fetch_object()){
echo = $line->colname ."\n";
}
}
echo "\n" . ' query: ' . $sql
or print_r($mysqliobj->info); # store las query
I'm trying to count entries in a database based on 2 basic criteria. It is returning a blank result, even though there are results to be found. Anyone have any idea what I am doing wrong here? I have tried it so many different ways and they all return no result. (If I enter the query directly in phpmyadmin it returns a result.)
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
$numericalResult = mysql_query($sql, $con);
$row = mysql_fetch_object($numericalResult);
$totalOrders1 = $row->total_count;
echo "My orders:" . $totalOrders1;
As others stated, make sure you sanitize variables before they go into query.
$sql = "SELECT * FROM orderOption3Detail WHERE orderDate = '" . $orderDate . "' AND studentID = '" . $studentID . "'";
$sql_request_data = mysql_query($sql) or die(mysql_error());
$sql_request_data_count = mysql_num_rows($sql_request_data);
echo "Number of rows found: " . $sql_request_data_count;
That's all you need.
Edited: providing full code corrected:
$con=mysqli_connect($db_host,$db_user,$db_pass,$db_name); // Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //global option 1
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='$orderDate' AND studentID='$studentID'";
//echo $sql;
$numericalResult = $con->query($sql);
$row = mysqli_fetch_object($numericalResult);
echo $row->total_count; //echo (int) $row->total_count;
Please test this and let me know. Good luck!
----- End Editing ----
Have you tested assigning values directly as a test in your SQL string, like:
$sql = "SELECT count(*) as total_count from orderOption3Detail WHERE orderDate='05/23/2012' AND studentID='17'";
Also, did you check if the date's format is correct, reading that $orderdate variable and testing it in PHPMyAdmin?
Did you read the $sql with values inserted and test in PHPMyAdmin and worked?
Also, check the connection to assure there is no problem there.
One more thing, sorry. You seem to be using the wrong syntax in your mysql_query statement. That way works for mysqli_query, and the parameters would be inverted. Try only:
$numericalResult = mysql_query($sql);
Provided you made the connection and database selection previously, like in:
$connection=mysql_connect($db_host, $db_username, $db_password);
if (!$connection)
{
$result=FALSE;
die('Error connecting to database: ' . mysql_error());
}
// Selects database
mysql_select_db($db_database, $connection);
Best wishes,
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
I am trying to display an entry from a MySql database which is selected by GET data.
if (isset($_GET["id"])){
$id=$_GET["id"];
$result = getSelectedBlog($id);
while($row = mysqli_fetch_array($result))
{
extract($row);
?>
<div class="headline"><?php echo $headline ?></div>
<div class="subtitle"><?php echo $subTitle ?></div>
<div class="content"><?php echo $content ?></div>
<?php
}
Here is the SQL statement:
function getSelectedBlog($id){
$con = mysqli_connect('localhost', 'root', '', 'michaelWebsite') or die('could not connect');
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "$id"';
$result = mysqli_query($con, $sql) or die('entry does not exist.:' . mysqli_error($con));
return $result;
}
As you can see, I am passing the get data as $id to the method that returns the result. However nothing is being returned. There are three entries at the moment, if I change $id in the SQL statement to either 1, 2 or 3 it will show the corresponding data but it just will not work with the $id variable.
The URL does end with the correct info ?id=1.
Please excuse me if it is something stupid, I have just been stuck on this for hours now!!
All of these answers will solve your problem, but none have mentioned or prevented SQL Injection.
In your case I recommend (assuming articleID is an integer field).
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "' . (int)$id . '"';
I'm also curious why you are using LIKE for an id field.
Note: Since you are using MySQLi, I'd encourage you to look at prepared statements.
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "'.$id.'"';
escape your var in simple quote
Try with this:
$sql = "SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'";
or with
$sql = 'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "' . $id . '"';
You need to use double quotes in order for php to correctly expand your variables :) so change your query to
$sql = "SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'";
Change
'SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE "$id"'
to
"SELECT * FROM tblArticle WHERE tblArticle.articleID LIKE '$id'"
Variables will be evaluated only if they're between double quotes "