How to generate next auto increment number in mysql using php? - php

I was trying to fetch next auto increment number in mysql using php. I tried this way:
<?
$q=mysql_query("SELECT * FROM `users`");
$next_auto_inc=mysql_num_rows($q)+1;
?>
But, this when any row is deleted don't work. I hope you got what I mean. How can I do this using php?

You can't do that fetching the table data. You have to fetch the table status to get the auto increment number using php. And that, you can do something like this:
$q = mysql_query("SHOW TABLE STATUS LIKE 'test'");
$row = mysql_fetch_assoc($q);
$next_increment = $row['Auto_increment'];
echo "next increment number: [$next_increment]";
Hope this helps :)
[Source]

Assuming that you have user_id column as primary key you can also try this:
$q = mysql_query('SELECT MAX(user_id) as user_id from `users`');
$row = mysql_fetch_assoc($q);
$next_auto_inc = $row['user_id'] + 1;

Related

Return frequency of string in MYSQL column with PHP

after searching for several questions, i'm still struggling with mysql queries in PHP, my current goal is to do a MYSQL query that counts how many repeated strings are in a column and then return this amount in a INT variable to be written in the database.
The current code looks like:
//Fetch value from form and uppercase the string
$glitter = utf8_decode(strtoupper($_POST['code_string']));
$magic = mysql_query("SELECT COUNT(*) FROM table WHERE CODE_STR = '$glitter'");
The next step is inserting the var $magic into a INT field in the database, however the value is always 0.
Where is my mistake?
Thanks.
mysql_query returns a resource on success, or FALSE on error.
try this
$magic = mysql_query("SELECT COUNT(*) as count FROM table WHERE CODE_STR = '$glitter'");
$row = mysql_fetch_assoc($magic);
$count = $row['count'];
Your approach is correct. What you need to do now is
Change your query from
$magic = mysql_query("SELECT COUNT(*) FROM table WHERE CODE_STR = '$glitter'");
to
$magic = mysql_query("SELECT COUNT(*) as total_num FROM table WHERE CODE_STR = '$glitter'");
mysql_fetch_assoc() Use the returned value from table
$magic_row = mysql_fetch_assoc($magic);
echo $magic_row['total_num'];
See
http://php.net/manual/en/function.mysql-fetch-assoc.php

how to get one record from a mysql database with php

i'am trying to get one cell from my mysql database.
this cell is unique because of the date and hour.
so if date and time is selected with a WHERE it should come back with one number.
I checked everything but it still doesnt work. i get zero returns.
does anyone see something wrong with my code?
$result2 = mysql_query("SELECT * FROM `chairs` WHERE `date` = '$date' AND `hour` = '$hour' ");
$row = mysql_fetch_array($result2);
$dbchairs = $row[$chairs];
echo $dbchairs;
You have undefined variable chairs in
$dbchairs = $row[$chairs];
If in DB is column called chairs, use:
$dbchairs = $row['chairs']; // key of $row array is column name
change this
$dbchairs = $row[$chairs];
to
$dbchairs = $row['chairs'];
You are using undefined variable $chairs as your index in $row array.
syntax: $row['name_of_the_column_in_database']

Insert random id into database

I'm trying to insert records in my database and I am using this code:
<?php
$con = mysql_connect('localhost','root','')
or die(mysql_error());
mysql_select_db ("my_db");
$patient_array = array();
$query = "SELECT * FROM accounts";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$patient_array[$row['account_id']] = array("lastname" => $row['lastname'],
"firstname" => $row['firstname']);
}
foreach($time_table as $tid => $t){
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor,
patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."',
'".$doc."', '".$tid."', '".$t["to"]."')";
mysql_query($sql);
}
?>
This one is properly inserting but for the "patient_id" I want to store random ids. $tid gives me random output but when I check the database, it's not the same; it's showing ids in descending order. I tried using Order by Rand() but I can't figure out how to make it working. Any idea? Or am I missing something?
Thanks!
EDIT: I am getting the patient_id from another table, which is the accounts table to be passed into appointment table. I was able to select random patient ids but how can I insert it to another table, in random order also.
For getting random id why cant you use the functoin uniqid() in PHP
$randomID = uniqid()
Please refer the following link,
Random/Unique ID
you can add an extra column called 'time' where you put the UNIX time for example so that when you order by the 'time' you get the random ids in the order you wrote them in the table..
I suggest you to add the time is really useful to have it stored somewhere!
if you want them not in random order but in a precise order I don't actually understand why you wanna use the random id though!
I would make a database field called id which has the
AUTO_INCREMENT attribute
You can add the column with the following command
alter table appointment add (id INT NOT NULL AUTO_INCREMENT);
Thank you for all your responses, but I've figured out what's the answer for this. Here's my code modification:
while($row = mysql_fetch_array($result))
{
//I changed this...
//$patient_array[$row['patient_id']] = array("lastname" => $row['lastname'], "firstname" => $row['firstname']);
//to this:
$patient_array[] = $row['patient_id'];
}
foreach($time_table as $tid => $t){
/*
removed this, since it's just an output to check what's happening inside
the 'rand'
echo array_rand($patient_array, 1);
echo $tid."====".$t["from"]." - " . $t["to"]."<br />";
*/
//added these...
$rand = array_rand($patient_array); //randomize patient id
$patient_id = $patient_array[$rand];
print_r($patient_id); //displays randomized ids
//and now was able to INSERT RANDOM patient ids
$sql = "INSERT INTO appointment (appt_id, appt_date, appt_time, appt_doctor, patient_id, appt_time_end) VALUES ('', '".$appt_date."', '".$t["from"]."', '".$doc."', '".$patient_id."', '".$t["to"]."')";
mysql_query($sql);
}

how UPDATE mysql row plus one and get the value

I updated with success
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
but how can I get the "queue2" value without opening a new request to MySQL
I can simply get the new value with this command
$selresult = mysql_query("SELECT * FROM $table WHERE `id` = '$getid'") or die(mysql_error());
but I'm afraid that the database can get new update again and i will get higher number
Any idea how to do it ?
you can use query to update the value.
mysql_query("UPDATE user_profile SET userpoints = userpoints + 1 WHERE user_id = '".$user_id."'");
See URL:-
PHP + MySQL transactions examples
Try this:-
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
You will need to use a transaction between the queries to be certain.
The docs for transactions are here. A good SO question that covers it in detail: PHP + MySQL transactions examples
Edit:
Looking at it from a different angle, why don't you do it in reverse though? It might save the need for a transaction (thought it is possible that you get multiple reads before a write):
Get the value for your queue2 value to display in the page from this:
mysql_query("SELECT * FROM $table WHERE `id` = '$getid'");
You have the true value now, so you can run:
$result = mysql_query("UPDATE $table SET `queue2` = `queue2` + 1 WHERE `id` = '$getid'");
No transaction and you know the value of the data before the update.

Echo a selected id from MySQL table

I have this
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
This echo's all id's found in the table.
How can I choose to echo only a selected id.
Say the second id found on the table?
EDIT
I think I have confused people and myself aswell.
Let me try to explain again.
Using the above query I can echo all results found in the table with echo $row['id'];
However I do not want echo all results, just selected ones.
You guys have suggested I use limit or a Where clause.
If I do this I will be limited to just one record. This is not what I want.
I want to echo a selection of records.
Something likes this
echo $row['id'][5], $row['id'][6], $row['id'][6]
But obviously this is incorrect syntax and will not work but hopefully you get what I am trying to do.
Thanks
If you only want the second row then you could change your query to use offset and limit e.g.
SELECT id FROM table LIMIT 1, 1
You could also use a for loop instead of the while loop and then put in a conditional.
UPDATE
Just noticed comments above - you also need to sort the PHP bug by changing mysql_fetch_array to mysql_fetch_assoc.
UPDATE 2
Ok based on your update above you are looking to get all of the rows into an array which you can then iterate over.
You can just use mysql_fetch_array and then use $array[0]. For example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
$ids = array();
while($row = mysql_fetch_array($result)) {
$ids[] = $row[0];
}
From what I can gather from your questions you should not be selecting all records in the table if you wish to just use the Nth value, use:
SELECT id FROM table LIMIT N, 1
That will select the Nth value that was returned. Note: The first result is 0 so if you wish to get the second value the Nth value should be 1.
mysql_data_seek() let's you jump to a specific data-set(e.g. the 2.nd)
Example:
$sql = "SELECT id FROM table";
$result = mysql_query($sql) or die(mysql_error());
//get the 2nd id(counting starts at 0)
if(mysql_data_seek($result,1))
{
$row=mysql_fetch_assoc($result);
echo $row['id'];
}
OR:
use mysqli_result::fetch_all
It returns an array instead of a resultset, so you can handle it like an array and select single items directly (requires PHP5.3)

Categories