How to get columns values after insert using php mysql? - php

In this code, after insert values to DB.I am doing select query for selecting invoiceNo($sql1= "select invoiceNo from invoices order by invoiceID desc limit 1"; ).Instead of selecting from DB how to get InvoiceNo?
For eg: Assume two users are there.Two users inserts InvoiceID at a same time.While doing "select invoiceNo from invoices order by invoiceID desc limit 1";this will get last coming invoiceID .I need to get specific invoiceID (for particular user) .How to get it?
$query = "select * from invoices order by invoiceID desc limit 1";
$result = $link->query($query);
$row = $result->fetch_assoc();
$invoiceNo = $row["invoiceNo"];
$getinvoiceNo = str_pad($invoiceNo + 1, 4, 0, STR_PAD_LEFT); //inserting like 0000
$sql = "INSERT INTO invoices (invoiceNo)
VALUES ('$getinvoiceNo')";
if ($link->query($sql) === TRUE) {
//echo "1";
$sql1 = "select invoiceNo from invoices order by invoiceID desc limit 1";
$last_id = mysqli_insert_id($link, $sql1);
$result1 = mysqli_query($link, $sql1);
$row1 = mysqli_fetch_array($result1);
echo json_encode($row1);
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysql_close($link);

If i understand your question correctly, you are concerned about possible data corruption from the concurrent update of the record.
I think you should give a look to mysql SELECT ... FOR UPDATE syntax, it should do what you ask: lock the selected row until an update is fired. Then the lock will be released.
For example:
SELECT table_field FROM table_name WHERE table_id_field = id_param FOR UPDATE
will lock the selected row until
UPDATE table_name SET table_field = table_field + 1 WHERE table_id_field = id_param

If you're looking to prevent collisions in invoice numbers, all you need to do is create your table as
CREATE TABLE invoices (
invoiceID INTEGER NOT NULL AUTO_INCREMENT,
other columns . . .
PRIMARY KEY (invoiceID)
);
Then when you do your INSERT, don't insert the invoiceID and let MySQL do it.
This will ensure that each new invoice has a unique invoiceID.

Related

For each query result add it into a table and give an ID php

I need help to insert my query results into another table and give it an id number per every result.
$GroupSize = $_POST['groupsize'];
//Connect to the Server+Select DB
$con = mysqli_connect($host, $user, $password, $dbName) or die("Nope");
if (isset($_POST['create'])) {
//assign group id to groups created
//insert groupinformation to table from userInformation group Id must increment by every group created
//$query ="Select RegistrationId from userInformation order by RAND() LIMIT ".$GroupSize;
$query = "INSERT INTO groupInformation SELECT RegistrationId FROM (SELECT RegistrationId FROM userInformation ORDER BY RAND() LIMIT ".$GroupSize.")";
$result = mysqli_query($con, $query) or die ("query failed " . mysqli_error($con));
while (($row = mysqli_fetch_row($result)) == true) {
echo $row[0].'<br>';
}
My table userInformation has a primary key on RegistrationId and a foreign key on RegistrationId in groupInformation. Group Id in groupInformation will generate the ID per result auto incrementally.
I know I need to this with a while loop or a foreach but I do not know how.
begin to Select what you want like as
$ stmt = $con->prepare("SELECT //Select what you want to select\\)
$ stmt->execute()
$ array = $stmt->fetch()
After u can insert to a new table like
$ stmt = $con->prepare(INSERT INTO groupinformation)
$ stmt->execute
Ucan't do a insert into and a select at the same row

how to get the id of last affected rows in php mysqldatabase?

My code
$query = "select * from others";
But it takes previous id . when I insert the first row , it takes the id value will be 0 , then again insert the second row, it takes the id value will be 1.
Please Use my simple code it will be helpful for you
$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
echo $row['id'];

How to fetch record from mysql using last inserted id?

This is what i tried and it works fine..
$sql = "SELECT * FROM patient where id = (SELECT max(id) FROM patient)";
result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
// output data of each row
while($row = mysql_fetch_assoc($result))
{
$patientid=$row["id"];
$patientname=$row["name"];
$patientrefer=$row["referto"];
$patientdisease=$row["disease"];
}
}
else
{
echo "0 results";
}
but whenever i replaced the query with
$sql = "SELECT * FROM patient where id = LAST_INSERT_ID()";
It always return 0 results.
In order to get last (latest) record from your table, you can do descending ORDER BY together with LIMIT:
SELECT * FROM patient ORDER BY id DESC LIMIT 0,1
You don't need LAST_INSERT_ID in that case at all. Moreover with concurrent inserts you cannot ensure that user's last insert is really the latest one by using LAST_INSERT_ID.

PHP SQL - Random Select 1 Row, Where ID = x

I have a MySQL database and I need a PHP to pull a random row. I have successfully created
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
This successfully randomly pulls a row; however, it is not limited to where region=2.
I need to be able to:
pull randomly when region=UK
pull randomly when region=UK or ##
(where ## is actually another region, for example, YK = Yorkshire)
Basically I need it to select rows randomly but ONLY when region=UK.
region is a label for one of my fields/collumns, and UK is the content of the VARCHAR in that for a number of rows.
I have the rest of the code sorted.
I have a simple database and the php as follows:
<?php
//Sample Database Connection Syntax for PHP and MySQL.
//Connect To Database
$hostname="carbonmarketing.db.9606426.hostedresource.com";
$username="MarketReadOnly";
$password="Read0nly1";
$dbname="carbonmarketing";
$usertable="ClientList";
$advertfooter = "advertfooter";
mysql_connect($hostname,$username, $password) or die ("<html>%MINIFYHTML4333ddb1f6ba50276851b9f9854a5c817%</html>");
mysql_select_db($dbname);
# Check If Record Exists
$query = "SELECT * FROM $usertable
WHERE region='UK'
ORDER BY RAND() LIMIT 1";
$result = mysql_query($query);
if($result)
{
while($row = mysql_fetch_array($result))
{
$advertfooter = $row["$advertfooter"];
echo "$advertfooter";
}
}
?>
But, it's just pulling randomly for all values of the region column
Let me know if it would help for you to see the database.
Make and array with your regions and implode them:
$region = array('UK', 'YK');
$implode = implode("', '", $region);
$query = "SELECT * FROM `".$usertable."` WHERE `region` IN ('".$implode."') ORDER BY RAND() LIMIT 1";
$query = "SELECT * FROM $usertable
WHERE region IN ('UK','YK')
ORDER BY RAND() LIMIT 1";

Php/MySQL help - random daily pick?

I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");

Categories