I am trying to get the last id which I entered to my database. Here is the code I use:
$test_query = "SELECT * FROM table ORDER BY id DESC LIMIT 1";
if ( mysql_query($test_query) ) {
echo 'OK!';
$results = mysql_fetch_array($test_query);
echo $results['id'];
print_r ($results);
}
The only output I have is the 'OK!'.
What do i do wrong?
You need to use the output of mysql_query in mysql_fetch_array.
$res = mysql_query($test_query);
if ($res === false) {
throw new Exception("query failed");
}
$row = mysql_fetch_array($res);
echo $row["id"];
Keep in mind that this reads only one row. If you want more use the while loop construction you can find here: http://php.net/mysql_fetch_array
If you just did an INSERT query use mysql_insert_id() to fetch the id. This is a feature of MySQL. This works in conjunction with the AUTO_INCREMENT option.
Also, if this is a new site you're building use mysqli_* functions instead of mysql_*. The latter is deprecated.
You can use this if you have an auto-increment field in the table:
SELECT LAST_INSERT_ID();
Related
I am fairly new to PHP.
What I want is not much. I just want to place a check on my page which goes to database and check for value 1 or 0. 1 means "enable" so page continues ; and 0 means "disable" and page dies.
someone suggested the following but it didn't work
$sql = mysql_query("SELECT * FROM members WHERE access= '1'");
$user = mysql_query($sql);
echo $user;
if ($user !=="1") {
echo "You are not the proper user type to view this page";
die();
}
Thank you so much for your time.
Firstly, you're using mysql_query() twice and that alone will cause a syntax error.
You're also not looping over results, so use the following to achieve what you want to do.
$sql = "SELECT * FROM members WHERE access= '1'";
$user = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($user)){
if ($row['access'] !=="1") {
echo "You are not the proper user type to view this page";
die();
}
else {
echo "You are the right type.";
}
}
If your query requires a db connection to the query, you will need to do:
$user = mysql_query($sql, $connection);
This assuming a mysql_ successful connection. However, that API is deprecated as of PHP 5.5 and deleted as of PHP 7.0 and note that different MySQL APIs do not intermix.
It's time to step into the 21st century and use either the MySQLi_ or PDO API.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
You may also have to select an actual row (or rows) instead of SELECT * FROM members
I.e.:
SELECT column_1, column_2 FROM members
Consult these following links http://php.net/manual/en/function.mysql-error.php and http://php.net/manual/en/function.error-reporting.php
and apply that to your code.
You can also achieve this with mysql_num_rows():
$result = mysql_query("SELECT * FROM members WHERE access= '1'");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
// do something
}
else {
// do something else
}
You might also want to add to the WHERE clause:
$result = mysql_query("SELECT * FROM members WHERE access= '1' AND column='x' ");
I'm trying to SELECT all rows as specified in the query below, but I think the issue is related to mysql_fetch_row, because in MYSQL Workbench the MYSQL query (yes I know I should be using PDO) shows all desired rows.
$result = mysql_query("SELECT zebra_id FROM zebra WHERE user_id = '$id' AND pref = '1'")
or die(mysql_error());
$array = mysql_fetch_row($result);
echo json_encode($array);
JSON Output (only showing 1 row):
["986"]
I tried changing to mysql_fetch_array, but that doesn't output all rows in the JSON encoded $array.
mysql_fetch_row() only fetchs one row as the name implies. So your error is obvious.
mysql_fetch_array() won't work unless you iterrate through the entire result set*. You just don't call it once and expect to get the entire result set in an array.
$result = mysql_query("SELECT zebra_id FROM zebra WHERE user_id = '$id' AND pref = '1'")
or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo json_encode($array);
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You have to do this in a loop. See this:
$result = mysql_query("SELECT zebra_id FROM zebra WHERE user_id = '$id' AND pref = '1'")
or die(mysql_error());
$array = array();
while($row = mysql_fetch_row($result)){
$array[] = $row;
}
echo json_encode($array);
And also I have to say that, do not use mysql_* functions anymore. These are deprecated officially. You have to use mysqli_* or PDO instead.
wish to check the last id (cat_id) in a table (category) and insert that result into a variable that I can echo.
My intention is to create a record last cat_id +1 as long as it doesnt already exist of course.
What I thought I should do was something like this;
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
echo ($result);
?>
But oh no, nothing so simple. The echo was only to check I had the correct result (in phpmyadmin it returns the desired number)
Then I was hoping to be able to, with a simple html form, was to ask if the user wanted to add a category through a text box:
addrec.html:
<form action="addrec.php" method="post">
Category: <input type="text" name="category">
<input type="submit">
</form>
addrec.php:
<?php
require "mydbdetails.php";
$new_id = $result + 1;
$query="INSERT INTO category VALUES ($new_id, 'Fruits')";
?>
You must first know as a developer, that mysql extension in php will be fully deprecated in the future as it is already in the newer php versions. So use instead Mysqli extension and PDO for sanitation and securer code for your database.
As it goes to your question:- Try the following ;
// Make a MySQL Connection
$query = "SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
//assign result to a variable
$result = mysql_query($query) or die(mysql_error());
//fetch result as an associative array
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['cat_id'];
You can assign it to avariable $row['cat_id'] = $catId; like that and use it .
echo $result[0]['cat_id'] i think
Please consider using PDO query Syntax instead of the old deprecated mysql_query.
If you make a PDO connection and store it in the $conn object ( pretty similar to what you already have in mydbdetails.php) just do:
$query=$conn->query("SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1");
$result=$query->fetchAll(PDO::FETCH_COLUMN,0);
echo ($result[0]);
First of all, you should really be using mysqli instead of mysql because mysql is deprecated and will be removed in PHP 5.5.
Of course the PDO would be better, but i think that you're so new that it would be a bit to much right now.
Basically, you're firing a Query, but you don't tell the query to what connection. You're doing this:
$result=mysql_query($query);
What it should be is
$result=mysqli_query($link, $query);
Where $link is the variable where you're setting up the database connection in the mydbdetails.php file.
Without the connection the Query doesn't know where to get the data from.
But if OOP isn't new to you, the answer from #amenadiel is better because it's an OOP way.
Further, there is no need for your $new_id = $result + 1; line.
IDs should almost always set to Auto Increament in the database, so this line will be done automatically in the database when you're adding a new dataset.
More information here
Hope this helps
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
$i;
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
var_dump($row); /* dump rows*/
/* or add to array to use later */
$results[$i] = $row; // add to array
$i++; // +1 the counter to increment the array
}
?>
Try to write your scripts in mysqli_ or pdo functions. Work around in mysql_ function (not recommended)
<?php
require "mydbdetails.php";
$query="SELECT cat_id FROM category ORDER BY cat_id DESC LIMIT 1";
$result=mysql_query($query);
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$cat_id = $row['cat_id'] + 1;
} else {
$cat_id = 1;
}
?>
cat_is is the primary key? If yes you can set that column as auto increment. You can try this
https://php.net/manual/en/function.mysql-result.php
I'm running the following query, expecting it to return an INTEGER, but it returns "Resource id #3"
What am I doing wrong?
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
echo $queryPlans;
There are actually 15 rows in this table, and I would like to return the number 15.
Any suggestions?
mysql_query will return a php resource(see: http://www.php.net/manual/en/language.types.resource.php).
The returned resource should then be passed to mysql_fetch_assoc or similar.
Since you are only getting the count, you can use the following:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$count = mysql_result($queryPlans,0,0);
echo $count;
You need:
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
$row = mysql_fetch_array($queryPlans);
echo $row[0];
mysql_query() isn't returning the result. It's returning a resource you can loop across and interrogate for rows (as above).
This is actually expected behavior according to the documentation:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
It's a regular select that returns one row with one column and should be treated as such. You can call mysql_fetch_array on the result:
$row = mysql_fetch_array($resource);
$count = $row[0];
mysql_query() returns a result resource. You need another function the get "valuable information" from that resource. In this case mysql_fetch_array()/mysql_fetch_row()/mysql_fetch_object as cletus pointed out. Or (since it's only a single value) mysql_result().
Any sql query may fail for various reasons. You should always check the return value of mysql_query(). If it's FALSE something went wrong and mysql_error() can tell you more about it.
$mysql = mysql_connect(...) or die(mysql_error());
mysql_selecT_db(.., $mysql) or die(mysql_error($mysql));
$query = "SELECT count(*) FROM infostash.rooms";
$queryPlans = mysql_query($query, $mysql) or die(mysql_error($mysql));
$cRows = mysql_result($queryPlans, 0);
echo $cRows;
If you are planning on using the full query later (e.g. select , rather than count()), you can save yourself a database hit by using mysql_num_rows() on the full query. Example:
$queryPlans = mysql_query("SELECT * FROM infostash.rooms");
$results = mysql_fetch_array($queryPlans);
echo "There were " . mysql_num_rows($queryPlans) . " results";
while($row = mysql_fetch_assoc($queryPlans)){
// Do stuff here
}
$queryPlans = mysql_query("SELECT count(*) FROM infostash.rooms");
mysql_num_rows($queryPlans);
http://us.php.net/manual/en/function.mysql-num-rows.php
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 :)