Can't Use Variables in mysql_query()? - php

This is about as basic as it gets guys and girls.
I have a very simple script that just will not work. I call the database and test it's connection, I do a query, store the result, and print the result.
The problem is that I can't seem to use any variables in my SQL statement.
Here's the code:
<?php
$rest_name = $_GET['rest_name']; // outputs 'Starbucks'
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '$rest_name'");
/* I've also tried these as well
$test = mysql_query("SELECT code_id FROM table_code WHERE restaurant = '".$rest_name."'");
*/
$mark = mysql_result($test,0);
echo $_GET['rest_name'].$mark;
?>
I echoed the query and it looks fine and run fine in the database. The $rest_name variable echos fine. The $_GET['rest_name'] echos fine. I am lost and confused on this.

1 - You can start with this.
$test = mysql_query("S....") or die(mysql_error());
This way you will see what error you are getting.
2 - you might want to avoid using a variable provided by the user in your query
$rest_name = mysql_real_escape_string($_GET['rest_name']);
otherwise user can insert their own sql commands;
3 - mysql_xxx functions are being deprecated, you might want to research pdo or mysqli to see how the new methods work.

Verify that you have a valid result set returned by msyql_query
$test = mysql_query("SELECT ... ");
if (!$test) {
die(mysql_error());
}
(It's possible you aren't connected to the MySQL instance, you are in the wrong database, the user you are connected as doesn't have permissions, etc.)
Check the resultset, before you use it.
NOTE: Don't use the mysql_ functions, use mysqli or PDO instead.

Related

Variables in Mysql Query

I am writing a PHP script in which i need to run a MySQL query. I opened the data connection and all such pleasantries are working fine. My only doubt is regarding the syntax of the following query, since it is not working. I have a php variable $post_id against which I am selecting from the database.
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
$result=mysql_query($query);
$req_id=$result[0];
You are not fetching the result.
So try this
<?php
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
$result=mysql_query($query);
while($row= mysql_fetch_array($result))
{
echo $row['needer'];//You can display your result like this.
}
Also mysql is depricated learn Mysqli or PDO.
For Mysqli function check this link http://php.net/manual/en/book.mysqli.php
For PDO function check this link http://php.net/manual/en/book.pdo.php
try this one, its better approach if you user SQL INJECTION
<?php
$query1="SELECT needer FROM needer_blood WHERE value_id='".mysql_real_escape_string($post_id)."'";
$result=mysql_query($query) or die(mysql_error()); // die only used in development , remove when you live this
$data = mysql_fetch_array($result) or die(mysql_error());
echo $req_id = $data['needer']; // $req_id = $data[0];
?>
Firstly, notice that your query variable is called $query1 and your mysql_query is using a variable called $query (variable mismatch?).
You can use mysql_fetch_assoc() to get an associative array from your query.
Using the following code should work, though you should do some checking to make sure that the $result[0] exists.
// Query String
$query1="SELECT needer FROM needer_blood WHERE value_id='$post_id'";
// Run the query
$result=mysql_query($query1) or die(mysql_error());
// Fetch Associative Array
$rows=mysql_fetch_assoc($result);
// Get result [0]: this could result in an error if your query result is empty.
$req_id=$rows[0];
Also, as others have pointed out, mysql is deprecated and you should update to MySQLi or PDO_MySQL if your server supports it. If not, change servers.
Also, as others pointed out, you should watch out for SQL injection. This StackOverflow answer adresses the issue well.

Cannot print data from MySQL Query with PHP

I am writing a PHP script that is supposed to interact with a MySQL database. On my local testing server, the code echos out what it is supposed to just fine, but in the live environment, I get an error saying Fatal error: Call to a member function fetch_array() on a non-object in [file path removed for security] on line 42. Here is my code from around line 42.
$query = "SELECT " . $data . " FROM mySchemaTable WHERE incrementId = " . $something;
$result = mysqli_query($conn,$query);
$row = $result->fetch_array(MYSQL_BOTH); // This line is 42.
echo $row['0'];
break;
I noticed a few problems with your code:
Firstly, you're mixing OOP and Procedural programming with MySQLi commands. Although PHP allows this, you'll want to make that uniform throughout. If you're using $conn = mysqli_connect(parameters here); you'll want to focus on procedural (change $result->fetch_array(MYSQLI_BOTH) to mysqli_fetch_array($conn, MYSQLI_BOTH); for instance). (I would assume you're doing this, so do this ^ change)
Else, if it's $conn = new mysqli(parameters); then you'll want to make it OOP based; instead of mysqli_query($sql); you'd use $conn->query($sql);, assuming $sql contains the query you want to run.
Secondly, echo $row['0']; should be echo $row[0]; unless the row you're returning is actually named 0, in which case disregard this.
Thirdly, and as a side note, it's a bad idea to directly insert variables into SQL queries, especially if they're user generated. You should look into sanitizing input or prepared statements to protect against SQL injection attacks.
Sanitizing Input Reference: What's the best method for sanitizing user input with PHP?
Prepared Statements: http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
The problem was solved without my intervention. It turns out that my code was fine as it was, but something was wrong with my host's MySQL. It's fixed now, and everything is working again.

Assign MySQL database value to PHP variable

I have a MySQL Database Table containing products and prices.
Though an html form I got the product name in a certain php file.
For the operation in this file I want to do I also need the corresponding price.
To me, the following looks clear enough to do it:
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
However, its echo returns:
Resource id #5
instead a value like like:
59.95
There seem to be other options like
mysqli_fetch_assoc
mysqli_fetch_array
But I can't get them to output anything meaningful and I don't know which one to use.
Thanks in advance.
You will need to fetch data from your database
$price = mysql_query("SELECT price FROM products WHERE product = '$product'");
$result = mysql_fetch_array($price);
Now you can print it with
echo $result['price'];
As side note I would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
If you read the manual at PHP.net (link), it will show you exactly what to do.
In short, you perform the query using mysql_query (as you did), which returns a Result-Resource. To actually get the results, you need to perform either mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_object on the result resource. Like so:
$res = mysql_query("SELECT something FROM somewhere"); // perform the query on the server
$result = mysql_fetch_array($res); // retrieve the result from the server and put it into the variable $result
echo $result['something']; // will print out the result you retrieved
Please be aware though that you should not use the mysql extension anymore; it has been officially deprecated. Instead you should use either PDO or MySQLi.
So a better way to perform the same process, but using for example the MySQLi extension would be:
$db = new mysqli($host, $username, $password, $database_name); // connect to the DB
$query = $db->prepare("SELECT price FROM items WHERE itemId=?"); // prepate a query
$query->bind_param('i', $productId); // binding parameters via a safer way than via direct insertion into the query. 'i' tells mysql that it should expect an integer.
$query->execute(); // actually perform the query
$result = $query->get_result(); // retrieve the result so it can be used inside PHP
$r = $result->fetch_array(MYSQLI_ASSOC); // bind the data from the first result row to $r
echo $r['price']; // will return the price
The reason this is better is because it uses Prepared Statements. This is a safer way because it makes SQL injection attacks impossible. Imagine someone being a malicious user and providing $itemId = "0; DROP TABLE items;". Using your original approach, this would cause your entire table to be deleted! Using the prepared queries in MySQLi, it will return an error stating that $itemId is not an integer and as such will not destroy your script.

PHP Retrieve Database Value

So i have this so far..
if(isset($_POST['Decrypt']))
{
$dbinary = strtoupper($_POST['user2']);
$sqlvalue = "SELECT `value` FROM `license` WHERE `binary` = '$dbinary'";
$dvalue = mysql_query($sqlvalue) or die(mysql_error());
}
I have a field where the user enters a binary code which was encrypted. (The encrypt part works). This is supposed to retrieve the value from the database. When ever i do it, instead of the value showing up, it says "Resource id #11".
There's nothing wrong with your quoting. In fact, everything looks right so far.
The thing is, right now $dvalue is just a resource to the SQL database. You have to fetch the contents with one more line:
$dvalue = mysql_fetch_array($dvalue);
In the future, you might want to start using PDO or MySQLi instead of the mysql functions, because those are deprecated as of 5.5.0. The advantage of PDO and MySQLi is that they offer security from SQL Injection, which is when users run their own SQL code by inputting something like x'; DROP TABLE members; --.
Don't use the mysql_ functions anymore. They are deprecated. Use PDO or MySQLi instead.
That being said, you are only running the query, and not retrieving any results. You will have to call a function like mysqli_fetch_array to get data from the resource ID that mysqli_query will return.
My advice is to go back to the tutorials and documentation and try again with one of these other extensions. Good luck.
Read this page: W3 Schools page on MySQL select useage. Basically $dvalue is a result set id and you'll need to actually fetch the array out of the database in another step. Also, mysql_* functions are deprecated. Lookup and use the mysqli_* functions instead.
while($row = mysqli_fetch_array($dvalue))
{
echo $row['value'];
echo "<br>";
}

Getting a basic PDO statement to execute

I am attempting to get the following PDO statement to work and running into issues. When I am trying to get the number of rows, I keep getting 0, yet I know there should be 1 row. When I ran it as a mysqli statement( before trying to change it to PDO) it worked perfectly.
Here is the code:
require_once ('pdo.php');
$isbn = $_POST['isbn'];
// check to see if the isbn is a "problem" isbn or not
$problem = $conn->prepare("select isbn, note from problem where isbn = :isbn");
$problem->bindParam(":isbn", $isbn);
$problem->execute();
print_r($problem);
$num_rows = $problem->rowCount();
print_r($num_rows); die;
EDIT: Here is pdo.php:
<?php
function db_connect()
{
$db = new PDO("mysql:host=localhost; db=bookcell_BCOS_final", "xxxxx", "xxxxx");
return($db);
}
?>
I know that my connection works, but I get 0 for $num_rows. What mistakes am I making here?
Besides a little quirk and a optimalisation your code looks fine to me. The posted value isbn could be the reasong that you are getting no data:
$problem = $conn->prepare("select isbn, note from problem where isbn = :isbn");
$problem->bindParam(":isbn", $_POST['isbn'], PDO::PARAM_STR); // <-- thats what parameter binding is for
$problem->execute();
print_r($problem);
$num_rows = $problem->rowCount(); // <-- gives the number of rows, not columnCOunt
print_r($num_rows); die;
The Syntax for $num_rows = $problem->columnCount(); is totally correct. You may try,
$problem->execute(array("isbn" => $isbn));
instead of bindParam.
for getting the no. of rows, you need to use pdo::rowCount() -- manual here
In PDO to verfiy if your execute statement did work, check the return value (bool):
$success = $problem->execute();
if (!$success) {
$arr = $problem->errorInfo();
print_r($arr);
}
Also you might be looking for rowCount() instead of columnCount() but I think the error handling is your furthermost issue.
Additionally you can make PDO throw an exception each time an error appears, compare:
Switching from PHP's mysql extension to PDO. Extend class to reduce lines of code
How do I raise PDOException?
Depending on the database driver and the mode it's running, PDO may not be able to give you a row count. Look carefully at the documentation for PDOStatement::rowCount():
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
This is because in many cases the database uses a cursor rather than fetching the full results and buffering them (which is how the old mysql_* functions behave). In this case the database doesn't know how many rows there are until you have looked at all the rows. Think of a cursor as something like a filesystem pointer--you can't know the filesize until you seek to the end of the file.

Categories