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.
Related
How could I return the values from this query as an array so that I can perform an action with the array?
$sql = mysql_query("SELECT username FROM `users`");
$row = mysql_fetch_array($sql);
How would I get the code to be like the following? Here, the user1 and user2 would be the usernames of the users selected from the above query.
$userarray = array("user1","user2");
Before I point out best practices, you need working code first. So I'll give you a simple solution first.
To run a query with the mysql extension the function is mysql_query, you can't pass the query text directly to mysql_fetch_array. Nextly mysql_fetch_array doesn't do what you think it does. mysql_fetch_array combines the functionality of mysql_fetch_row and mysql_fetch_assoc together by storing the key names of the resulting columns along with their numeric indexes. The mysql_fetch_array function does not return an array with all rows from your query. To get all rows from the query, you need to run mysql_fetch_array in a loop like so:
$sql = "SELECT username FROM `users`";
$result = mysql_query($sql);
if(!$result){echo mysql_error();exit;}
$rows=array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
print_r($rows);
Nextly, do note that the mysql_* functions are deprecated because the mysql extension in PHP is no longer maintained. This doesn't mean MySQL databases are deprecated, it just means the database adapter called mysql in PHP is old and newer adapters are available that you should be using instead, such as mysqli and PDO.
Next point, it is bad practice to rely upon short tags as it can be disabled by php.ini settings, always use either <?php ... ?> or <?= ... ?> for easy echoing which isn't affected by short tags.
Please read up on some mysqli or PDO simple examples to get started with one or the other. The mysqli extension is specific for MySQL while PDO (PHP Data Objects) is designed as a generic adapter for working with several kinds of databases in a unified way. Make your pick and switch so you're no longer using the deprecated mysql_* functions.
You would need to use a foreach loop to do it:
$userarray = [];
foreach($row as $single)
{
array_push($userarray, $single['username']);
}
and if can, try to use this MySQLi Class, it's very simple to get what you want from the database.
$db = new MysqliDb ('host', 'username', 'password', 'databaseName');
$userarray = $db->getValue('users', 'username', null);
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.
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>";
}
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.
I've got the following code:
<?php
if(!empty($error_msg))
print("$error_msg");
else
{
require_once("../include/db.php");
$link = mysql_connect($host,$user,$pass);
if (!$link)
print('Could not connect: ' . mysql_error());
else
{
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
$res = mysql_query($sql);
print("$sql<br>\n");
print_r("RES: $res");
mysql_close($link);
}
}
?>
In one word: it does not work. mysql_query doesn't return anything. If I try the same
query within php_myadmin, it works. It does not insert anything either. Also tried it as
user root, nothing either. Never had this before. Using mysql 5.1 and PHP 5.2.
Any ideas?
mysql_query will return a boolean for INSERT queries. If you var_dump $res you should see a boolean value being printed. It will return TRUE for a successful query, or FALSE on error. In no cases it ever returns NULL.
In addition, never pass input data (e.g.: $_POST) directly to an SQL query. This is a recipe for SQL injection. Use mysql_real_escape_string on it first:
$language = mysql_real_escape_string($_POST['language']);
$sql = "INSERT INTO language SET language='$language'";
And don't forget to quote your array indices (e.g.: $_POST['language'] instead of $_POST[language]) to prevent E_NOTICE errors.
You need to specify a database so the system knows which database to run the query on...
http://php.net/manual/en/function.mysql-select-db.php
Without selecting a database, your data will not be inserted
mysql_query returns a boolean for INSERT queries. If used in string context, such as echo "$res", true will be displayed as 1 and false as an empty string. A query error has possibly occured. Use mysql_error() to find out why the query has failed.
$sql = "insert into languages values(NULL,'$_POST[language]','$_POST[country_code]');";
This is very bad practise, as a malicious user can send crafted messages to your server (see SQL Injection).
You should at least escape the input. Assuming your column names are named 'language' and 'country_code', this is a better replacement for the above code:
$sql = sprintf('INSERT INTO LANGUAGES (language, country_code) VALUES ("%s","%s")',
mysql_real_escape_string($_POST['language']),
mysql_real_escape_string($_POST['country_code'])
);
For a description of the mysql_real_escape_string function, see the PHP Manual. For beginners and experienced programmers, this is still the best resource for getting information about PHP functions.
Instead of using $_POST directly, I suggest using the filter_input() function instead. It's available as of PHP 5.2.
With an INSERT query, mysql_query returns true or false according as the query succeeded or not. Here it is most likely returning false. Change the line print_r("RES: $res"); to print_r("RES: ".(int)$res); and most likely you will see it print RES: 0.
The problem may be that MySQL expects a list of column names before the VALUES keyword.
Also, you appear to be inserting POST variables directly into SQL - you should read up on SQL injection to see why this is a bad idea.
--I retract the quote comment, but still not good to directly insert $_POST values.--
Second, I don't think i've seen print_r quite used like that, try just using an echo.
And mysql_query is only expected a boolean back on an INSERT, what are you expecting?
Now ive got this:
$language = mysql_real_escape_string($_POST['language']);
$country_code = mysql_real_escape_string($_POST['country_code']);
$sql = "insert into shared_content.languages (id,language,country_code) values(NULL,$language,$country_code);";
$res = mysql_query($sql);
print("$sql<br>\n");
var_dump($res);
print(mysql_error());
mysql_close($link);
And the output:
insert into shared_content.languages (id,language,country_code) values(NULL,NETHERLANDS,NL);
bool(false) Unknown column 'NETHERLANDS' in 'field list'