What is the difference between mysql_query() and mysql_result()? - php

I'm unsure whether I should be using mysql_result() or mysql_query() when running a query on a database. Does it make a difference in the case below?
$usertable = 'tableName';
$colName = 'columnA';
$xlookup = 'columnB';
// Connect to Server
$con = mysql_connect($hostname, $username, $password);
// select db
mysql_select_db($dbname);
// run query
$result = mysql_query("SELECT $colName FROM $usertable where $xlookup = 5");
// pass results to webpage
$a = 51;
$x = array($a, $a, mysql_result($result));
echo json_encode($x);
At the moment, whether I use this or not does not make a difference as neither work, but I had thought an error would stop the code from running.
I was trying to use the below code to identify any errors but am not sure if it is correct or not.
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die("<html><script language='JavaScript'>alert('Unable to run query'), $message</script></html>");
}

mysql_query does the query and returns a resultset.
mysql_result returns the rows from that resultset for you to play with.
Look up some examples here.
mysql_result has the distinction of being able to return specific fields, but as other poster noted is slower than the other fetch functions.

mysql_query and mysql_result are two completely different functions which do completely different things.
mysql_query sends an SQL query to the data base.
mysql_result gets a value from a query result according to its row (and optionally a column number, default to zero) number.
That said you should use mysql_fetch_row if you are going to be using more than one datum for each row.

They are different functions. mysql_query executes a query (string) and returns a resource object that you can use to retrieve information from. mysql_result is one of the helper functions that allow you to get that data from the resource. So you'll need both.
Or actually you don't. Once you've used mysql_query, you can use other functions, like mysql_fetch_row too for retrieving data. Most of these functions perform better and more efficient than mysql_result.

Related

MySQL Random output does not work

So I want to pull a random record off my DB:
mysql_connect("127.0.0.1","my_shop","xxxxxx");
mysql_select_db("my_shop_db");
error_reporting(E_ALL && ~E_NOTICE);
$random_record = "SELECT * FROM products ORDER BY RAND() LIMIT 1";
$random_product = mysql_query($random_record) or die ($random_record);
echo $random_product['id'];
What I tried so far:
DB Connection works 100%
Tables exist, have exact wordings and contain data
DB User has rights to pull Data
What is wrong with my script?
That can't work. You make a query thats it. You should fetch the data first with mysql_fetch_assoc or another function to get an output.
And the mysql_* functions are deprecated you should start with mysqli or PDO and prepared statements.
Obligatory comment that mysql_* is deprecated and not safe and should not be used anymore.
mysql_query returns a resource object NOT an array. You need to fetch the data into an array so you can access it.
$random_record = "SELECT * FROM products ORDER BY RAND() LIMIT 1";
$random_product = mysql_query($random_record) or die ($random_record);
//fetch data
$data_array = mysql_fetch_assoc($random_product);
echo $data_array['id'];
print_r the array so you understand the structure and how to access the element you want.
A lot of folks on here (correctly) point out that mysql should no longer be used, then go on to answer the question using mysql. I think it's worthwhile to show you how easy it is to make the change to mysqli. Using dan08's answer as a jumping off point:
//set up connection, save it into the $link variable
$link = mysqli_connect("127.0.0.1","my_shop","xxxxxx", "my_shop_db");
//your query, same as before
$random_record = "SELECT * FROM products ORDER BY RAND() LIMIT 1";
//almost the same syntax as mysql_*, but with the $link added in to specify the connection
$random_product = mysqli_query($link, $random_record) or die ($random_record);
//fetch data
$data_array = mysqli_fetch_assoc($random_product);
echo $data_array['id'];

counting rows in php with sql

For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.

echo statement not showing result after getting variable from $_post in php mysql

I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.

Counting the values of rows in a column and using the total value in PHP

I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];

Problem Checking a Unique Indentity within MySQL Database

I am trying to verify that a string is unique within a MySQL column. Here is the code sample:
<?php
$con = mysql_connect("hostname", "username", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("table_name", $con);
if (!mysql_num_rows(mysql_query("SELECT * FROM table_name WHERE unique_string = '123456'
LIMIT 1"))) {
die('This string is not unique.');
}
mysql_close($con);
?>
In this code sample I have input the value 123456 as an example. This example assumes that the string 123456 already exists in the column unique_string. Therefore, it should die and return the statement "This string is not unique." Sadly, it does not. Do you know why? Is there a better way to get this check done?
It's generally unwise to chain your function calls as you have. Particularly with database calls. The mysql_*() functions expect certain things, like statement handles, to be passed in. But they can return a boolean FALSE instead of a handle if there's a problem. This FALSE gets passed in instead of a handle and then everything's broken.
A general rule is to always assume your query will fail somehow, and program defensively:
$sql = "SELECT ....";
$result = mysql_query($sql) or die(mysql_error());
$rows = mysql_num_rows($result);
if ($row !== 0) then
die("Not unique");
}
Beyond that, your query statement does look to be syntactically correct. Why not see what it's returning?
$row = mysql_fetch_assoc($result);
var_dump($row);
and see exactly what's being matched. Maybe you DON'T have that value in the table and are mistaken in thinking that it's there.
Select count(*) from yourtable where mycolumn = 'unique string'
You should now test whether this returned a 1
You use "table_name" also for the DB. Is this correct? If not, mysql_select_db() fails, and any query will fail too, because no DB is selected.

Categories