I'm creating a mobile library app, and for one function of the app I am trying to receive the bookID for all books checked out by a certain user. I would like to be able to echo back the results from the query in a string format (preferably with spaces in between each separate book id) so I can deal with the data later on within the app.
Many of the answers I have found online have simply shown how to execute the query, but not how to use the data afterwards. Sorry if this is a simple question to answer, I am a huge novice.
<?php
require "conn.php";
$email = $_POST["email"];
$mysql_qry = "SELECT * FROM user_data WHERE email like '$email'";
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID LIKE $user_id ORDER BY bookID DESC";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$result2 = mysqli_query($conn, $mysqlqry2);
}
else
{
echo "Error, user name not found";
}
$conn->close;
?>
You could append your results into an array and display values using implode():
<?php
require "conn.php";
$email = $_POST["email"]; // You may test here : if (isset($_POST['email']))
$mysql_qry = "SELECT * FROM user_data WHERE email = '$email'";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$user_id = $row["user_id"];
$mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out
WHERE userID = $user_id ORDER BY bookID DESC";
$result2 = mysqli_query($conn, $mysql_qry2);
if(mysqli_num_rows($result2) > 0)
{
$ids = [];
while ($row = mysqli_fetch_assoc($result2)) {
$ids[] = $row['bookID'] ;
}
echo implode(" ", $ids) ; // print list of ID
}
else
{
echo "No books checked out!";
}
}
else
{
echo "Error, user name not found";
}
$conn->close;
NB: I used your code here, but, you should have to look to parameterized queries to prevent SQL injections.
Your query $mysql_qry2 should be defined after to get $user_id.
Your LIKE $user_id could be replaced by =.
First thing first, always sanitize your data:
$email = filter_var( $_POST['email'], FILTER_SANITIZE_EMAIL );
$user_id = preg_replace( "#[0-9]#", '', $row['user_id'] );
Use
DISTINCT bookID instead of DISTINCT(bookID)
From your query: $mysql_qry2 = "SELECT DISTINCT(bookID) AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY bookID DESC";
If you're not getting any result or the returned result is empty but the user_id does exist, then I think the query format is wrong.
What you should do instead
Change the ORDER BY: The query may be correct but mysql returned an empty result because the result order does not match.
Try this
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY userID DESC";
"SELECT DISTINCT bookID AS bookID FROM books_checked_out WHERE userID LIKE $user_id ORDER BY `primary_key_here` DESC";
Replace <strong>`primary_key_here`</strong> with the primary key name.
Run the query without conditionals and inspect the result
$query = mysqli_query( $conn, "SELECT bookID FROM books_checked_out DESC" );
var_dump( $query );
Use the result to inspect the rest of the query.
Rather than using your own protocol/format use something like JSON or xml in your response to the request.
This will give you better maintainability in the long run and allow you to easily handle the response in the browser with javascript, and most browsers will give you a nice display of JSON objects in the dev console.
You'll have to extract the user id from the result of the first query or you could do a joined query instead.
$email = validate($POST['email']); //where validate() will try to prevent sql injection
//joined query
$query =
" SELECT bookID FROM user_data
INNER JOIN books_checked_out on user_data.user_id = books_checked_out.userID
WHERE user_data.email='$email'
";
//not sure whether that should be user_id or userID looks like you have mixed conventions
//books_checked_out.userID vs user_data.user_id ... check your database column names
//loop through results
// may be empty if user email doesn't exist or has nothing checked out
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
$response[] = ['bookID'=>$row['bookID']];
}
echo json_encode($response);
When receiving the result in php you can use json_decode() or in javascript/ajax it will automatically be available in your result variable.
if things aren't working as expected it can be a good idea to echo the actual sql. In this case
echo 'SQL IS: '.$query;
and test it against your database directly (phpmyadmin/MySQL-Workbench) to see if you get any results or errors.
I created a mysql query to check if user is banned or not and if he's the system give him return false. But it wont get the information.
public static function checkban($username)
{
if(LOGINCHECKBAN == false)
{
$vusername = engine::securyt($username);
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$getNOW = mysql_query($getIdBYname);
$IDbyNAME = mysql_free_result($getIdBYname);
$queryforban = mysql_query("SELECT * FROM bans WHERE data = '".$IDbyNAME."' LIMIT 1");
$query = mysql_num_rows($queryforban);
if($query == 0) {
return true;
} else {
return false;
}
}
}
Note: engine::securyt($username) is the form type to get his username when he try to login.
What can be wrong on my code?
edit: I belive that "mysql_free_result" can be the problem, but im not sure what i need to put on replace of it.
mysql_free_result() frees a mysql result set. It does not actually retrieve data from the result.
You will want something like:
$getIdBYname = "SELECT id FROM players WHERE username='".$vusername."' LIMIT 1";
$result = mysql_query($getIdBYname);
$row = mysql_fetch_assoc($result);
if($row) { //a user was found
//$row['id'] is the found user
$result = mysql_query("SELECT COUNT(*) cnt FROM bans WHERE data = '". $row['id'] ."' LIMIT 1");
$row = mysql_fetch_assoc($result);
return ($row && $row['cnt'] == 0);
} else {
// no user; return something appropriate
}
However, if all you need is to determine is whether a particular user name is banned (and not actually get their user id), you can do that directly in the database with one query:
SELECT COUNT(*)
FROM players p
INNER JOIN bans b ON b.data = p.id
WHERE p.username = $username;
WARNING: Note that using mysql_* functions is strongly discouraged for new code (since mysql_* has been removed in PHP 7), and directly including variables in your query strings is a pretty major security vulnerability. You should look into using prepared statements/parameterized queries with mysqli or PDO.
I have this code:
$local_id = $_GET['id'];
$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"];
// the rest
}
how can i check if $local_id does not exist in the db and display an error?
mysql_num_rows
if(mysql_num_rows($sql) == 0) {
//Show error
}
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
echo 'error';
You can use the following query:
"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)
This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.
This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as #Ryan Doherty correctly posted.
Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).
If you fail to do so, you are a possible victim for SQL Injection.
You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.
So I'll try to clearly explain my goal first:
First, I want to query one table in my database for a list of usernames.
Second, I want to take those usernames, and query another table in the database and return only the rows in which these usernames appear in the username field.
Finally, I want to take this output (in JSON array form right now), and return it to the requesting client.
My query looks like this right now:
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
This works when the WHERE statement yields 1 result. So if I only get one returned userA, it works fine. But if I get multiple, I get a bunch of errors.
Here is the code in its entirety:
if (isset($_POST['username'])) {
$username = $_POST['username'];
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("TagDB");
$query = mysql_query("SELECT * FROM tagusers WHERE username =
(SELECT userA FROM friendtable WHERE userB = '$username')");
}
while ($e = mysql_fetch_assoc($query)) {
$output[] = $e;
}
$output = json_encode($output);
print $output;
I get the following error on the query line:
*Warning: mysql_query() [function.mysql-query]: Unable to save result set in C:\wamp\www\tag\appgetfriendinfo.php on line 21*
So all I really need to know is, how would I write that query in MySQL so that I get returned an array of rows?
You don't need a subquery at all, you'll usually get better performance out of a join. Make sure you have indexes defined on tagusers.username, friendtable.userA and friendtable.userB
SELECT
tagusers.*
FROM
tagusers
INNER JOIN
friendtable
ON
tagusers.username = friendtable.userA
AND
friendtable.userB = '$username'
Use the IN keyword.
$query = mysql_query("SELECT * FROM tagusers WHERE username IN
(SELECT userA FROM friendtable WHERE userB = '$username')");
Use either the IN clause, or a JOIN like in this example:
$query = sprintf("SELECT tu.*
FROM TAGUSERS tu
JOIN FRIENDTABLE ft ON ft.usera = tu.username
WHERE ft.userB = '%s'",
mysql_real_escape_string($_POST['username']));
$result = mysql_query($query);
$output = json_encode($result);
What's the best way with PHP to read a single record from a MySQL database? E.g.:
SELECT id FROM games
I was trying to find an answer in the old questions, but had no luck.
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);
There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die() statement allows you to see errors if they occur.
Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xx or something similar to get only one row and not more. Also you can access your id like $row['id']
Using PDO you could do something like this:
$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
echo $id;
}
You obviously should also check whether PDO::query() executes the query OK (either by checking the result or telling PDO to throw exceptions instead)
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT query, use a WHERE statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example)
Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:
$sql = "SELECT id FROM games LIMIT 1"; // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];
This difference requires MySQL to select only the first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.
One more answer for object oriented style. Found this solution for me:
$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;
gives back just one id. Verify that your design ensures you got the right one.
First you connect to your database. Then you build the query string. Then you launch the query and store the result, and finally you fetch what rows you want from the result by using one of the fetch methods.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$singleRow = mysql_fetch_array($result)
echo $singleRow;
Edit: So sorry, forgot the database connection. Added it now
'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:
with mysqli
$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();
with Zend Framework
//Inside the table class
$select = $this->select()->where('user_id = ?', 1);
$row = $this->fetchRow($select);
The easiest way is to use mysql_result.
I copied some of the code below from other answers to save time.
$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);
$num_rows = mysql_num_rows($result);
// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
$value = mysql_result($result, i, 'id');
echo 'Row ', i, ': ', $value, "\n";
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli('localhost', 'tmp', 'tmp', 'your_db');
$db->set_charset('utf8mb4');
if($row = $db->query("SELECT id FROM games LIMIT 1")->fetch_row()) { //NULL or array
$id = $row[0];
}
I agree that mysql_result is the easy way to retrieve contents of one cell from a MySQL result set. Tiny code:
$r = mysql_query('SELECT id FROM table') or die(mysql_error());
if (mysql_num_rows($r) > 0) {
echo mysql_result($r); // will output first ID
echo mysql_result($r, 1); // will ouput second ID
}
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
Better if SQL will be optimized with addion of LIMIT 1 in the end:
$query = "select id from games LIMIT 1";
SO ANSWER IS (works on php 5.6.3):
If you want to get first item of first row(even if it is not ID column):
queryExec($query) -> fetch_array()[0];
If you want to get first row(single item from DB)
queryExec($query) -> fetch_assoc();
If you want to some exact column from first row
queryExec($query) -> fetch_assoc()['columnName'];
or need to fix query and use first written way :)