I'm using pdo and I have a query like this
$stmt=$db->query("SET #update_id := 0;
UPDATE table SET column = something, id = (SELECT #update_id := id)
WHERE condition
LIMIT 1;
SELECT #update_id;");
It is supposed to update a row and return the id.
I'm sure the query itself is working because I ran it in phpmyadmin and it returned a column named #updated_id with the value of the updated row like this:
| #updated_id |
|------------------|
| *correct id* |
I want to fetch the value of #updated_id and store it in a php variable.
I tried $stmt->fetchColumn(); and $stmt->fetchColumn(); but I get SQLSTATE[HY000]: General error.
I've been searching for something to work but I can't find anything.
so anybody knows how to store the value of #updated_id in a php variable?
thanks
As Petah suggested in the comments, you need to iterate through each rowset until you get to the SELECT statement you want to fetch.
Given you example above, this should work:
$stmt=$db->query("SET #update_id := 0;
UPDATE table SET column = something, id = (SELECT #update_id := id)
WHERE condition
LIMIT 1;
SELECT #update_id;");
$stmt->nextRowset();
$stmt->nextRowset();
$update_id = $stmt->fetchColumn();
<?php
$id = 123;
$query = "UPDATE table SET column = something, id = ? WHERE condition LIMIT 1;"
$st = $db->prepare($query);
$st->execute(array(
$id
));
$result = $st->fetch(PDO::FETCH_ASSOC);
var_dump($result);
Do you tried something like this?, fetching the modified statement
Related
why it's not working..
i want to update my table in database this is my code.
for ($i=0; $i <83 ; $i++) {
$link="this is test".$i;
$sql = "UPDATE tbl_gallery_images SET thumbnail_url='$link' WHERE gallery_id=1";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
echo $link."<br>";
}
when i echo that link it's show 100% right but in db just update 82 number in all rows even it is in loop.
thanks in advance.
UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1
As it is, this query updates column thumbnail_url in all records that have gallery_id = 1. Running the same query 84 times in a loop results in the same set of records being updated again and again in each iteration, with an increasing thumbnail_url. After the last iteration, all records where gallery_id = 1 end up with thumbnail_url = 'this is test83.
A sensible solution would be to add another criteria in the WHERE clause, in order to update just one record per iteration. Assuming that you have some integer column called id to disambiguate the records where gallery_id = 1, you would typically go:
`UPDATE tbl_gallery_images SET thumbnail_url = '$link' WHERE gallery_id = 1 AND id = $i`
I am trying to loop through an array ($lineup_selected) that corresponds to a player row in a database. For each player I would like to execute an UPDATE query to the database that adds the value of $submissions_selected to the total_picks column. I am struggling with the code as it fails to execute the query. Any help please?!
// Select team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
// Loop through and update total_picks for each player in database present in lineup_selected array
$player_picks_query = "SELECT full_name, total_picks FROM table WHERE team=$team_selected";
$result = mysqli_query($conn, $player_picks_query);
while($row = mysqli_fetch_assoc($result)) {
$player = mysql_real_escape_string($row["full_name"]);
$add_player_picks = "UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name = '$player'";
}
why not:
UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE team = '$team_selected'
this way you have only one query to execute and let your database do the looping. Else you would first select some records and then have your database update each one of them to update the record.
I assume the fullname is unique. If not, it would mean your version can have the update-query modify multiple records each time and so my approach is invalid
-- and I seem to repeat a lot of the comments when stating to sanitize and escape your input to be save(r).
edit:
combined it should come to:
// set team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
$updatequery = "UPDATE table
SET total_picks = total_picks + ?
WHERE team= ?";
$stmt = mysqli_prepare($updatequery);
mysqli_stmt_bind_param($stmt, "is", $submissions_selected, $team_selected);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
Myself I am more into the pdo approach, but syntax should be like this.
In your select request you have a team that is obviously a String. So, maybe you can try your request like : "SELECT full_name, total_picks FROM table WHERE team='$team_selected'"
I don't know if PHP is smart enough to put the quotes.
I think it will be better if you use only an update statement.
First of all you implode your array
$lineup_selected = array("player1", "player2", "player3");
$players='".implode("','",$lineup_selected )."';
Now you can update the table
$updateStmt="UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name in (".$players.") and team=".$team_selected.";
my MYSQL Database looks like this:
short -- idnumber--position
abc.......8765...........4
def........7453...........1
abc.......7398...........5
def........7542...........2
I have the idnumber and want to Update all with the the same 'short' as the idnumber. Update should be Position-1.
i have idnumber: 8765 its position should be 3 and position of id 7398 should be 4
How do i do it correctly? My Code dont work and i got no echo
<?php
$pdo = new PDO('mysql:host=localhost;dbname=testdb1', 'root', '');
$idV = $_GET['id'];
$statement = $pdo->prepare("UPDATE idtabelle SET position = position-1 WHERE short IN
(SELECT short FROM idtabelle WHERE idnumber = :idV)");
$statement->bindParam(':idV', $idV);
$statement->execute();
while ($row = $statement->fetch(PDO::FETCH_ASSOC))
{
echo $row['short'];
};
?>
try this. you can give a start id.
UPDATE idtabelle
SET position = position -1
WHERE idnumber = 8765
AND position > 2
ORDER BY position ASC;
You're attempting to fetch a row result from an UPDATE statement which doesn't return rows. (Your SELECT subquery is returning it's rows only to the UPDATE query -- the UPDATE result is the only thing returned to you.)
What you should be doing is something like:
...
$statement->bindParam(':idV', $idV);
if ($statement->execute())
echo $statement->rowCount() . " rows updated";
else
echo "Update failed with error: " .print_r($statement->errorInfo(), TRUE);
...
If you need to get the value of "short" in addition to updating, then you should probably do it as two queries instead - a SELECT to get "short", and an UPDATE to update the rows after.
If i try to run your query on sqlfiddle.com i get the error: "You can't specify target table 'idtabelle' for update in FROM clause".
But you can wrap your subquery into another subquery (derived table):
UPDATE idtabelle
SET position = position-1
WHERE short IN (SELECT short FROM (
SELECT short
FROM idtabelle
WHERE idnumber = :idV
) temp);
http://sqlfiddle.com/#!9/7d88a/1
Ok, don't know if this is simple in practice as it is in theory but I want to know.
I have a single INSERT query were by in that query, i want to extract the AUTO_INCREMENT value then reuse it in the same query.
For example
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
$getId = mysqli_insert_id();
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
Apparently, am getting a blank value(I know because the mysqli_insert_id() is before the query, but I've tried all i could but nothing has come out as i want. Can some please help me on how to achive this
From my knoweldge this cant be done. Because no query has been run, MySQL is unable to return the ID of said query.
You could use a classic approach, pull the id of the previous record and add 1 to it, this is not a great solution as if a record is deleted, the auto increment value and the last value +1 may differ.
Run multiple queries and then use the insert_id (MySQLi is different to what you are using, you are best using $db->lastInsertId(); as mentioned in the comments.
Run a query before hand and store it as a variable;
SELECT auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
I strongly recommend Option 2, it is simply the cleanest and most reliable method for what you are looking to achieve.
It seems the value required for $display_type is :$display_type + (max(id) + 1).
In order to get the max_id you'll have to do this query before :
$sql = "SELECT id FROM articles ORDER BY id DESC LIMIT 1";
$result = mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
// $maxid[0] will contains the value desired
// Remove the mysqli_insert_id() call - Swap $getid by ($maxid[0] + 1)
// and u're good to go
N.B. update the name of ur primary key in the query $sql.
EDIT :
Assuming the weakness of the query and the quick resarch i did.
Try to replace $sql by (don't forget to Update DatabaseName & TableName values) :
$sql = SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND TABLE_NAME = 'TableName';
That Should do it . More info on the link below :
Stackoverflow : get auto-inc value
I don't think this can be done. You'll have to first insert the row, then update display_type, in two separate queries.
Thanks guys for your opinions, out of final copy, paste, edit and fix; here is the final working code(solution)
`
//values to be inserted in database table
$a_name = $mysqli->real_escape_string($_POST['a_name']);
$details = $mysqli->real_escape_string($_POST['details']);
$display_type = $mysqli->real_escape_string($_POST['display_type']);
//Select AUTO_INCREMENT VALUE
$sql = "SELECT `AUTO_INCREMENT`
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'chisel_bk'
AND TABLE_NAME = 'articles'";
$result = $mysqli->query($sql);
$maxid = $result->fetch_array(MYSQLI_NUM);
$getId = $maxid[0];
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO articles (a_name,details,display_type,date_posted) VALUES('$a_name','$details','$display_type$getId',CURRENT_TIMESTAMP)");
This happens to do the magic!!!
`
I'm trying to use the answer given at : How to get ID of the last updated row in MySQL?
I want the ID of the row which was updated. But the following doesn't work giving the error
Fatal error: Call to a member function fetch_assoc() on a non-object.
$query = "
SET #update_id := 0;
UPDATE locations SET owner_player_id='$player_id', id=(SELECT #update_id := id)
WHERE game_id='$game_id' LIMIT 1;
SELECT #update_id;
";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
$location_id = $row['update_id'];
Thanks
Edit:
$mysqli->error gives You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE locations SET owner_player_id='5', id=(SELECT #update_id := id) WHERE gam' at line 1
Your SQL has failed, that is why your subsequent fetch_assoc() method is also failing.
You will want to look into running your query without using the variables (#update_id) as you are intending, and look at using mysqli::$insert_id.
Without knowing what it is you are trying to do exactly, it's hard to be more specific.
Have to use mysqli::multi_query not mysqli::query. Also then have to use mysqli::next_result and mysqli::store_result to get the correct data.
$query = "SET #update_id := 0; UPDATE locations SET owner_player_id='$player_id', id = ( SELECT #update_id := id ) WHERE game_id='$game_id' LIMIT 1; SELECT #update_id;";
$mysqli->multi_query($query) or die($mysqli->error);
$mysqli->next_result();
$mysqli->next_result();
$result = $mysqli->store_result();
$row = $result->fetch_assoc();
$location_id = $row['#update_id'];