how to get ID of inserted rows and update rows? - php

I want to get ids in my table then update
id row is auto increment
if (isset($_POST['reply'])) {
$reply = $_POST['reply'];
$answers = $db->query("SELECT * FROM table_name");
while($answers_ = $answers->fetch_object()){
if($get_answer = $db->query("UPDATE table_name SET answer ='$reply' WHERE question_id = '$answers_->question_id' LIMIT 1")){
echo "done";
}
}
}
I know my code is wrong its update all rows with the same value i want to update only one row

use mysqli_insert_id() — Returns the auto generated id used in the last queryn
$get_answer = $db->query("UPDATE table_name SET answer ='$reply' WHERE question_id = '$answers_->question_id' LIMIT 1")
$last_id = mysql_insert_id();

Related

How to get columns values after insert using php mysql?

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.

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'];

Getting last value of a field in mysql

I am trying to get the last value of a field during a new registration.
before insert data into the table, I want to create a user id number according to the last registered user's id number. to do that I use this:
//to reach the last value of userID field;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$value = $row['userID'];
echo "$value"; //not resulting here
}
$userID = $value+1;
so, the userID becomes 1.
The weird thing is, I could capable to use exact same code in another php file and works fine.
I would like to say that, rest of the code works fine. No problem with db connections or any other things you can tell me.
Note that: When I run the same query line in the mysql interface, I can get the value I want. I mean $sql line.
Your problem is in this code:
{
$svalue = $row['userID'];
----^
echo "$value"; //not resulting here
}
$userID = $value+1;
Change to $value.
But the right answer is to define userID to be auto-incrementing. That way, the database does the work for you. After inserting the row, you can do:
SELECT LAST_INSERT_ID()
To get the last value.
I solved the problem. Here;
$sql = "SELECT userID FROM loto_users ORDER BY userID DESC LIMIT 1";
$result = mysql_query($sql);
$user_info = $result->fetch_assoc();
$value = intval($user_info["userID"]);
$userID = $value+1;
Thanks everyone.
If you mark the userID field as autoincrement in you mysql table.
You won't need to set the userID and db increase the userID for you. You can get the assigned userID using the mysql_insert_id() function. Here is an example from php.net
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Here is another example for your case
mysql_query("INSERT INTO 'loto_users'('username',...) values('usernameValue',...)");
echo "New User id is ".mysql_insert_id();

Why this if else condition is not working properly?

I am using if else condition with foreach loop to check and insert new tags.
but both the conditions(if and alse) are being applied at the same time irrespective of wether the mysql found id is equal or not equal to the foreach posted ID. Plz help
$new_tags = $_POST['new_tags']; //forget the mysl security for the time being
foreach ($new_tags as $fnew_tags)
{
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
while($rowq = mysqli_fetch_array($sqlq)) {
$id = $rowq['id'];
if($id == $fnew_tags) { //if ID of the tag is matched then do not insert the new tags but only add the user refrence to that ID
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$fnew_tags','1')");
}
else
{ //if ID of the tag is not matched then insert the new tags as well as add the user refrence to that ID
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags) values('$fnew_tags','1','1')");
$mid_ne = mysqli_insert_id($db3->connection);
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$mid_ne','1')");
}
}
}
i think you are inserting
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags)
values('$fnew_tags','1','1')");$mid_ne = mysqli_insert_id($db3->connection);
and then you are using while($rowq = mysqli_fetch_array($sqlq))
which now has records you just inserted therefore your if is executed
I'm pretty sure the select query below will always return the same record.
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
I think most of the time it will goes to the else, which execute the 2 insert.
Shouldn't you write the query like below?
select * from o4_tags where id = $fnew_tags limit 1

Can't get SQL Update to work using PHP

I'm trying to get php to update a MySQL table using UPDATE statement but it simply won't work. Here's the code I wrote:
$add = "1";
$counter=mysql_query("SELECT * FROM frases WHERE id = '".$id."'");
while ($ntcounter=mysql_fetch_array($counter)) {
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id);
}
As you can see, I am basically trying to update the SQL record to keep track of how many times a specific content ID was visited.
Thanks!
Use an alias in your SQL query (It is not mandatory, but it makes the query much more readable.)
SELECT * as count FROM frases WHERE id = '".$id."'"
And you can now access to your variable
$ntcounter['count']
So the result :
$add = "1";
$id = (int)$id
$counter = mysql_query("SELECT * as count FROM frases WHERE id = '".$id."'");
while ($ntcounter = mysql_fetch_assoc($counter)) {
mysql_query("UPDATE frases SET count = '".($ntcounter['count']+$add)."' WHERE id = '".$id);
}
You don't really need two queries. You should just be able to update like this
mysql_query("UPDATE frases SET `count` = `count` + 1 WHERE id = ".$id);
You didn't close the single quote at the end of the update statement:
mysql_query("UPDATE frases SET count = '".$ntcounter[count]+$add."' WHERE id = '".$id."'")

Categories