Get the last Id from database to a string/Int variable - php

I have to get the biggest id to a string or an int variable.
That is how I'm doing it:
$sql = "SELECT id FROM table ORDER BY id DESC LIMIT 1";
$list = mysql_query($sql) or die (mysql_error());
$lst = mysql_fetch_array($list);
$resId= $lst[0];
ResId is that variable.
Is this going to work?
Is there a better way to do it?
There is no AUTO_INCREACMENT!

If you don't auto increment or in any other way organize your id:s, there is no way to know which was the last one. (Unless you get the last inserted id when you're doing an insert query.)
Your query returns the greatest id, but if you haven't structured your code/table so that the greatest id is the last - then it won't return the last id obviously (oh well, it could).
As for your question if it will work. Why don't you simply try it out? You're much more likely to learn from trying your self than asking people for answers all the time.

If last id is the biggest id (as I see from your query), then you can also use:
$q = 'select max(id) as max_id from `b_iblock_element`';
$q_res = mysql_query($q);
$row = mysql_fetch_assoc($q_res);
$max_id = intval($row['max_id']);
And don't forget that mysql_* functions are deprecated and will be removed soon.

Related

Retrieve table ID from selected row

So I've been stuck on this for a while and I can't find anything on google for this specific thing.
I have this small snippet of code
$link = mysqli_connect("localhost", 'username','password',"database");
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Which should select the latest table by order of id's right?
Well what I want to do is return this id. So if I have 5 items/rows I want to grab the latest (5 in this case) id of the table, and return it. With the eventual goal of using this returned id in javascript but that's a worry for later, right now I just want it in plaintext where the result should only be the id.
This is probably a duplicate question but I can't for the life of me find what I should google to get there
EDIT:
I guess I should clarify further. I know I'm able to do
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
but whenever I try to actually retrieve it/print it its returned as a string instead of the ID.
EDIT 2: I, thanks to some comments, have managed to figure it out. Sorry for the badly worded everything, I'm new to this and as I said don't know how to word it.
SOLUTION:
After just throwing away the $sql thing I added:
$result = mysqli_query($link,"SELECT * FROM `uploads`");
Then I simply did
echo mysqli_num_rows($result);
To echo out the number of rows/what I called the "ID".
Sorry for all the confusion, thanks to those that tried to help. To the others there's no need to be rude.
If I understood your question correctly, you want to get the ID field only, so you have two options:
Option 1 (Recommended)
Given your code
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Change it to:
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
This way, your getting just that ID field you're after. Nothing else is returned from each row.
Option 2
Keep your sql query as it is, and get the ID field from each row in your results (it's an array, so you can retrieve only one field by using its index or name).
Of course, I assume there's an ID field in your table!
Just select the ID.
SELECT id
FROM uploads
ORDER BY id DESC
LIMIT 1;
Simply select what you want.
$sql = "SELECT id FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
The * means you want to select every column there is. However, SQL gives you the possibility to select the specific columns you want. You could also do something like
$sql = "SELECT id, name, title, somethingelse FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
and you'd receive these 4 fields as an array.

order by id not working with me

I have made " news & updates " simple script
my query is:
$query = mysql_query("SELECT * FROM a_commants WHERE postid='$postid' ORDER BY id DESC LIMIT 0,10");
it shows last comment
i want to make it show all comments or at least 10 comments
if i change it to:
$query = mysql_query("SELECT * FROM a_commants WHERE
postid='$postid'");
it shows first comment only
idk whats wrong :(
I think that the problem is in your php code, not MySQL.
The query seems fine, as long as you have more than one comment, but it seems that you are not iterating through results, just printing the first row you get from db.
This should show last 10 comments:
$res = mysql_query("SELECT * FROM a_commants WHERE postid='$postid' ORDER BY id DESC LIMIT 0,10");
while($row = mysql_fetch_array($res)){ // iterate through results
print_r($row); // print the row
}
And you should definitely switch to mysqli or PDO, and sanitize your inputs.
The mysql_* functions are deprecated and going to be removed from PHP.

How to use count in php?

I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this
$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";
Why, the result of nors is 6 not 2, although I only have 1 data?
mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...
$no = "SELECT COUNT(ID) AS count FROM member";
$result = mysql_query($no);
$row = mysql_fetch_object($result);
$nors = $row->count;
You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.
edit: #andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.
If you're using this to generate the next ID number for a new member, you should look at making ID an auto_increment field instead - as it stands, it's possible that you'll get two members signing up at the same time, and both getting assigned the same ID
Replace this line
$nors = mysql_query($no);
By these lines :
$result_handler = mysql_query($no);
$result = mysql_fetch_array($result_handler);
$nors = $result[0];
If your id field is set to be an auto number you don't need to insert it. MySql will handle that for you. Anytime you add a new row the autonumber is incremented. If you delete a row the autonumber does not decrement.
If you currently only have 1 row but you've added and deleted rows then your insert will produce a row with an ID that is not consecutive.

What's the most efficient way to count rows in a table?

Is it more efficient to use:
$sql = 'SELECT COUNT(*) AS count FROM users';
$odbcResult = OdbcExec($sql);
#odbc_fetch_row($odbcResult);
$count = #odbc_result($odbcResult, 'count');
or to use:
$sql = 'SELECT * FROM users';
$odbcResult = OdbcExec($sql);
$count = odbc_num_rows($odbcResult);
The former. The server is doing the work. It may already know the answer without counting,
The later requires all the rows to be returned to your program over the network (and into memory).
Populate a table with 10^x elements with x>=6 and see the time that takes.
$sql = 'SELECT COUNT(id) AS count FROM users';
$odbcResult = OdbcExec($sql);
#odbc_fetch_row($odbcResult);
$count = #odbc_result($odbcResult, 'count');
or some other index field besides id. Its a little faster than COUNT(*), but the count method is the way to go. If you need to do something with the results, method 2 is faster, but only needing count this is the one you want.
-edit- Added keyword of index before field. True comment below, made the assumption that there was an id index column (should have an index somewhere at any rate)
The first method is definitely faster. But COUNT(id) being faster than COUNT(*) - questionable. They usually are exactly the same, and there are cases when COUNT(id) is actually slower (see: http://www.mysqlperformanceblog.com/2007/04/10/count-vs-countcol/)

how to return array for mysql_query?

// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.

Categories