How to get ID of updated row? [duplicate] - php

This question already has answers here:
How to get ID of the last updated row in MySQL?
(12 answers)
Closed 1 year ago.
I would like to know the ID of the updated row and I tried this:
$sql = $db->prepare("UPDATE `timeslots` SET `service` = ? WHERE `status` = ?");
$sql->bind_param("is", 0, "open");
$sql->execute();
if ($sql->execute()) {
echo "ID: ".$db->insert_id."<br />";
}
But the result is everytime this instead of the ID:
ID: 0
ID: 0

The documentation for insert_id clearly states:
Returns the ID generated by an INSERT or UPDATE query on a table with a column having the AUTO_INCREMENT attribute.
Your query does not generate a new ID. You can't use $db->insert_id as there was no new ID reported by MySQL server.
You can trick MySQL into providing this value. Just reset the ID to the value that it had previously by regenerating it again.
$sql = $db->prepare("UPDATE `timeslots`
SET `service` = ?, Id=LAST_INSERT_ID(Id)
WHERE `status` = ?");
See How to get ID of the last updated row in MySQL?

Related

How to see if mysql replace or insert my query [duplicate]

This question already has answers here:
Find out if REPLACE statement has replaced or just inserted in MySQL
(3 answers)
Closed 4 years ago.
if I have a query with field 1 being a primary key:
$rep = "Replace into table (field1,field2) values ('value1','value2')";
$stmt = $db->query($rep);
Is there a way to tell if mysql inserted the row, or found and replaced the row?
For Posterity:
$rowCount = $stmt->rowCount();
if $rowCount == 1 it was an insert, if $rowCount == 2, it was a replace.
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
To achieve this type of task mysql provide us DUPLICATE KEY UPDATE.
Below is the example how you will create new record if record is not exists in database otherwise it will update record
$rep = "INSERT into table (primaryField,field2) values ('value1','value2') ON DUPLICATE KEY UPDATE primaryField=VALUES(primaryField)";
$stmt = $db->query($rep);
For more detail you can read this
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
I think this will help you.

If statement condition not running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am checking the for the user_id (it is held in a session) - this is working. Then I am running a SELECT query for that user for the database table click_count. I am checking to see if that user has any records within it, ie: $page_count. If not, I want my INSERT statement to run to add that user to the database table along with other data.
The part I do not understand is it seems that my UPDATE query is always running. For example no matter which user I login with my query only updates the only user in the database table. IE: Bob is the only user in the click_count table, if I log in with Pete, Bob's record is being updated.
I have tested the value for $page_count and it equals 0, so my INSERT should be running. I have also tried if ($page_count === 0) {
Does anyone see anything I am missing?
$curPage = $_SERVER['PHP_SELF'];
$clicks = 0;
$setup = 0;
$page_total_count = 0;
var_dump($user_id);
$click_sql = "
SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$click_stmt = $con->prepare($click_sql);
$click_stmt->execute(array($user_id, $curPage));
$click_stmt_rows = $click_stmt->fetchAll(PDO::FETCH_ASSOC);
$page_count = $click_stmt->rowCount();
foreach ($click_stmt_rows as $click_stmt_row) {
$setup_status = $click_stmt_row['setup'];
$page_total_count = $click_stmt_row['page_count'];
}
if ($page_count == 0) {
$click_insert_sql = "
INSERT INTO click_count
(user_id, page_url, page_count, setup)
VALUES(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE page_count=page_count+1;
";
$click_insert_stmt = $con->prepare($click_insert_sql);
$click_insert_stmt->execute(array($user_id, $curPage, 1, $setup));
}
else {
$click_update_sql = "
UPDATE click_count
SET page_count=page_count+1
WHERE user_id = ?
AND page_url = ?
";
$click_update_stmt = $con->prepare($click_update_sql);
$click_update_stmt->execute(array($user_id, $curPage));
}
Table
click_count
CREATE TABLE `click_count` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`page_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`page_count` int(11) NOT NULL,
`setup` int(5) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user_id` (`user_id`),
UNIQUE KEY `page_url` (`page_url`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Since there is only the one user in the table, there is no record "to insert/update", therefore
ON DUPLICATE KEY UPDATE failed you silently.
A regular UPDATE will suffice:
I.e. and as an example:
UPDATE table SET col_x = 0|1 WHERE col_y = ? // (boolean 0-1)
Note:
If ever you wish to increase a column by counting later on, the syntax would be:
UPDATE table SET col_x = col_x + 1 WHERE col_y = ?
In regards to your asking about how you could improve on your code:
#Fred-ii- Thanks. Yes, it is working now how I want, but if there are ways to improve the code I am always willing to try to learn it. I just remembered people in the past saying that I didn't need the update query at all with the duplicate key update. – Paul
You could use named placeholders :name rather than ? since they are easier to keep track of, but this is of course a matter of opinion that I feel is also shared by many and not just myself.
Footnotes/credits:
I would like to also give credit to the following comment:
"If you always fall into update indicates that $page_count is not zero.. Try to echo() it to see maybe.. I would probably first try to add another user into click_count table and then it may become easier to see where it goes wrong.. – johnyTee"
where the OP responded with:
"#Fred-ii- I figured it out. I used johnyTee's advise and tried adding another user to the database manually and it wouldn't let me because of the unique index for the page_url column. I then removed the unique index from it and now it works perfectly. Thanks for the help! – Paul"
from PHP PDO doc http://php.net/manual/en/pdostatement.rowcount.php
PDOStatement::rowCount() returns the number of rows affected by a
DELETE, INSERT, or UPDATE statement.
if you need th number of rows in select you should use somethings like
$sql = "SELECT *
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn();
It may be '0' (a string). You can use intval to convert it to an integer.
$page_count = intval( $click_stmt->rowCount() );
http://php.net/manual/en/function.intval.php
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
try like this:
$sql = "SELECT count(*)
FROM click_count
WHERE user_id = ?
AND page_url = ?
";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
//insert
}else {
//update
}
}

How to delete particular columns data in database using php mysql [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 7 years ago.
Hi iam trying to delete certain columns data from database.Here is my code for delete query.
//getting column id by comparing the id need to delete the data from that row.
$id=$_GET['id'];
$res = "DELETE rental_annual_rent,
rental_block,
rental_street,
rental_area,
rental_town,
rental_state,
rental_pincode
FROM house_details
WHERE house_details_id='$id'";
$result=mysql_query($res);
if(mysql_affected_rows()){
echo "successfully deleted";
session_start();
header("Location:property.php");
}else{
echo "Failure";
}
First iam inserting house_details data into database but i need to delete only particular data from that columns
What you want is an UPDATE, not a DELETE since you want to keep the row, but just clear/blank/unset certain columns within the row.
$res = "UPDATE house_details SET
rental_annual_rent = NULL,
rental_block = NULL,
rental_street = NULL,
rental_area = NULL,
rental_town = NULL,
rental_state = NULL,
rental_pincode = NULL
WHERE house_details_id='$id'";
Note that you should really be sanitizing your id input before using it in the query, you should parameterize it, and you should also migrate from the mysql library to mysqli or PDO

How can I change this code to INSERT instead of UPDATE if content doesn't exist? [duplicate]

This question already has answers here:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).

How to check if ID exists in database, otherwise insert it into database?

I have a code which generates a 6 digit random number with the code mt_rand(100000,999999); and stores it in the variable $student_id. I check if the number exists in the database with the following code.
if($stmt = mysqli_prepare($connect, "SELECT id FROM students WHERE id = ? LIMIT 1")) {
mysqli_stmt_bind_param($stmt, "i", $student_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $db_id);
mysqli_stmt_fetch($stmt);
}
if(mysqli_stmt_num_rows($stmt) == 1) {
echo "The ID exists.";
} else {
// Insert $student_id into database
}
This code can insert the ID into the database if mysqli_stmt_num_rows($stmt) == 0. But, if the ID already exists, it won't generate a new 6 digit random ID, it won't check if that ID already exists in the database, etc. I can imagine that I would have to use some kind of loop which will keep generating a random ID untill it doesn't exists in the database and then insert it into the database. I've read about a few loops (like while or for), but I don't have any idea how to use them.
Can anyone help me out with this or help me in the right direction?
Cheers
if you don't want to use autoincrement field, you can change your query in this way:
SELECT id FROM students WHERE id = ? limit 1
becames
SELECT count(id) FROM students WHERE id = ?
So you can check if the result is > 0 (exists) or not (not exists)
I created a simple PHP solution for this, while Bohemian answer is valid for a MySQL approach, here is a way to do it using do...while loop as the questionnaire wanted.
<?php
do {
$unique_id = mt_rand(100000, 900000);//generates 6 random numbers
$query = mysqli_query($mysqli, "select * from users where unique_id='$unique_id'");
} while(mysqli_num_rows($query) > 0);// repeats loop till generated id is not found
//php insert query comes here
?>
If you just need 6 digits, use an auto increment column, but have it start at 100000 instead of the usual starting value of 1.
You can do it at the time you create the table:
CREATE TABLE MYTABLE (
ID INT NOT NULL AUTO_INCREMENT,
-- other columns
)
AUTO_INCREMENT = 100000;
See this demonstrated on SQLFiddle.
Or if the table already exists with an auto increment column, you can set it:
ALTER TABLE MYTABLE AUTO_INCREMENT = 100000;

Categories