MySQL Random output does not work - php

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'];

Related

MySQL will not SELECT * FROM database

When I select all from my database, it only returns one row. I have changed it to select "column name" from database where "blank" = 1 and set multiple rows to have "blank" = 1 and it still only returns one row.
Here is my code:
<?php
$link = mysqli_connect("host", "database", "password", "database");
if (mysqli_connect_error()) {
die("There was an error, Please try again");
}
$query = "SELECT * FROM `news`";
$result = mysqli_query($link, $query);
$imageTest = mysqli_fetch_array($result);
?>
When I test this and print out the array with
<?php print_r($imageTest); ?>
It only comes back with one row (there are currently 3 test rows in the database)
I know Im probably missing something super small. Ive never really worked a project that I needed to select more than one row of items in a column.
I have another database being used in the same project that Im not having any issues with in its intended function but when I went to that one and tested the same thing, it returned the same results.
As per official documentation, mysqli_fetch_array fetch a single row from the result set every time it's called. Go for the following code to retrieve all of them:
$rows = array();
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result))
$rows[] = $row;
print_r($rows);
mysqli_fetch_array fetches a single row from the result set.
What you're looking for is mysqli_fetch_all (or a while loop with mysqli_fetch_array ).
I would advise against using mysqli_* functions, and suggest using PDO.
Please refer to the following resources as to why I hold this opinion:
mysqli or PDO - what are the pros and cons?
https://phpdelusions.net/pdo/mysqli_comparison

password issue with database change

I am changing my database to add an "sex" column and after, I can't log into the my site. So I look into the get_passwd() function, and I see $passwd = $row[5] is causing the problem.
I fixed it, but is there better way to do this function, even if I adding column into the database?
function get_passwd($link, $login) {
$sql = "SELECT * FROM user WHERE email='$login'";
$result = mysql_query($sql, $link);
$row = mysql_fetch_array($result);
$passwd = $row[6];//this is the problem!
//echo $passwd;
return $passwd;
};
You're MYSQL functions are deprecated.
You should be afraid of MYSQL Injections.
... But here is a way to make the world of MYSQL safer ...
PDO - http://php.net/manual/de/book.pdo.php
Example:
$db = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", "$db_user", "$db_pass");
$query = $db->prepare("SELECT username, password FROM user WHERE email = ? LIMIT 1");
// you should know which columns you are selecting
// LIMIT to make sure you don't select 2 rows.
$query->execute(array($login));
$row = $query->fetch();
echo $row["password"];
//return $row["password"];
$db = null;
Use mysql_fetch_assoc instead of mysql_fetch_array. It will return keyed array with column names as keys.
I'm guessing that everyone will tell you that it is no longer recommended to use these functions and you should switch to something like PDO, for example.
But since you might need to maintain some old application with legacy code I'm guessing that we can also stay on point and give an answer. You can use a function like mysql_fetch_assoc and the returned value will be an associative array, so you'll be able to use $row['password'] instead of $row[6]. There's also mysql_fetch_object.
Again, when you look at those manual pages please pay attention to the big notice on the red background at the top.
mysql_fetch_assoc allows you to perform a mysql query and use the response object as a key[value] array.
function get_passwd($link, $login){
$sql="SELECT * FROM user WHERE email='$login'";
$result=mysql_query($sql, $link);
$row=mysql_fetch_assoc($result);
$passwd = $row['password']; <- use the column name here
//echo $passwd;
return $passwd;
};
Find out more at the documentation page below:
http://php.net/manual/en/function.mysql-fetch-assoc.php

mysqli query in WHILE loop

1.) Can you nest a msqli_query inside a while loop?
2.) If yes, why would the PHP below not write any data to the precords table?
If I echo a $build array variable it shows properly, but the mysqli insert writes nothing to the table in the DB. THe code does not error out anywhere, so what am I missing about this?
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
//echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords (precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass) VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')");
};
Thanks for any help.
** P.S. - This code is meant to move certain values from a TEMPORARY table/session variables, over to a permanent record table, but the loop is needed since there is more than one product in the cart associated with the user/session.
yes you can use it in a loop and
you may wanna add mysql_error() function to find out what's wrong with it and try to fix it or by adding the error to the question so we can tell you what to do
$data = mysqli_query($con,"SELECT * FROM Cart WHERE Buyer_ID='$_SESSION[cid]' AND Cart_Date='$_SESSION[cdate]'");
while($build = mysqli_fetch_array($data))
{
// echo $build[idex]."<br>";
mysqli_query($con,"INSERT INTO precords(precord,Buyer_ID,Account,Purchase_Date,Item_Number,Item_Qty,Item_Title,Item_FPrice,Item_FFLFlag,ccpass)
VALUES ('$build[idex]','$build[Buyer_ID]','$build[Cart_Date]','$build[Item_Number]','$build[Item_Qty]','$build[Item_Title]','$build[Item_FPrice]','$build[Item_FFLFlag]','N')")
or die (mysql_error());
};
in a simplified form when you want to fetch data from a database to display in html list I intentionally added mysqli ORDER BY which have only two order ASC[ascending] and DESC[descending] and I also used mysqli LIMIT which i set to 3 meaning that number of result fetch from the database should be three rows only
I concur with the answer of ali alomoulim
https://stackoverflow.com/users/2572853/ali-almoullim
MY SIMPLIFIED CODE FOR THE LOOPING WHILE MYSQLI ORDER BY AND LIMIT
$usersQuery = "SELECT * FROM account ORDER BY acc_id DESC LIMIT 3";
$usersResult=mysqli_query($connect,$usersQuery);
while($rowUser = mysqli_fetch_array($usersResult)){
echo $rowUser["acc_fullname"];
}

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'];

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

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.

Categories