Find and UPDATE value in mysql php - php

hello i need find my target row in database (phpmyadmin) and update 1 column in that row.
$stmt = $db->prepare("SELECT * FROM users WHERE user LIKE '%{$username}%'");
$stmt->execute();
$result = $stmt->fetchAll();
$db_exp = $result['0']['expdate'];
i find my target with this code but i need update that i can show column now

Use UPDATE:
UPDATE users SET expdate = :newValue WHERE user LIKE :userName

Related

Check which columns were modified in an UPDATE query

When we update a MySQL record with php, we can check if it has effect using:
$mysqli->affected_rows;
But how do I check which column has been modified?
Example, in my table have the columns: id / name / age
In a record we have the data: 1 / Woton / 18
If I send an: UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'
Only the age field has changed. How can I determine this?
You cannot directly get the updated columns from the query result.
It can be get from some php query. Firstly we will have to select the row from database which we are going to update in a array variable. Than run the update query for the same row.
Lastly get the same row from database from select query in the new array variable.
Finally we get two arrays.
We can get the updated column with the array_diff_assoc php function.
See the below code for the same.
$sql = "SELECT * from mytable where id=1 limit 1";
$prev = mysqli_fetch_assoc(mysqli_query($conn, $sql));
//Get the column data in the array. Before update.
$sql = "UPDATE mytable SET name = 'Woton', age = '20' WHERE id = '1'";
$conn->query($sql);
// Update data
$sql = "SELECT * from mytable where id=1 limit 1";
$updated = mysqli_fetch_assoc(mysqli_query($conn, $sql));
// Again run the select command to get updated data.
$UpdatedColumns=array_diff_assoc($updated,$prev);
In a different note: If QueryLog has been enabled in the DB then you (or your script in PHP or Python or any) can easily see/read which part of the content has been updated and even you can monitor the DB.
The good news is, even you can target which table, which query etc.

PHP loop through array to update SQL database

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.";

Mysql update query for update all users data

I want a Mysql query to update all users 'status' filed in 'user' table. I can update one user by running following query.
Table
What I tried
update user set status = 1 where id = 1 and type = 'viber'
Do I need to run the above query inside a loop to update all users data?
I want a query like following
update user set status = 1 where id = 1 and type = 'viber' and id = 2 and type = 'twitter' ..
your help is much appreciated.
Just
update user set status=1;
Updates your whole table.
If you want to just update the status for all records then below query is useful for that.
update user set status=1;
The WHEREclause is used to extract only those records that fulfill a specified criterion. but here you don't want that .so just use this query to update all the records
update user set status=1;
just use:
$update = mysqli_query("UPDATE user SET status = 1")or die(mysqli_error());
if this not works, you can select all data and then update each row by setting user id like this :
$select = mysqli_query("SELECT * FROM user")or die(mysqli_error());
while($row = mysqli_fetch_array($select)){
$id = $row['id'];
mysqli_query("UPDATE user SET status=1 WHERE id='$id' ");
}

Use mysql_insert_id in single query

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!!!
`

PDO get last selected row

Is there a method to get last select ID in a similar way to lastInsertId?
For example:
<?php
$stmt = $db->prepare('SELECT * FROM users WHERE user_id = :user_id');
$stmt->bindValue(':user_id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
$user_id = $db->lastSelectId('user_id'); // what can I do here?
?>
Obviously in the above example I could simply get the last selected row ID with $user->user_id but that's not the question. Any ideas?
If you want to select the last inserted row from your database table, there is no point selecting all rows and then looking for the last in a loop. Besides, user_id should be primary key, in which case you query should only return one row.
If user_id is an auto-incremented field, your query should go like SELECT * FROM users ORDER BY user_id DESC LIMIT 1, this will return the user with the largest user_id.
I will also suggest the you save the timestamp of when users are inserted and then you can do ORDER BY date_added DESC LIMIT 1 this will work irrespective of the ORDER of the user_ids.
No, there is no other way than reading $user->user_id. No magic functions to get the last id of a select.
And it's probably because there is no need for it, since the select returns that value itself. You've shown in your question how easy it is to read the id.
Try With following -
$stmt->insert_id;
Refer the below link -
Using PHP, MySQLi and Prepared Statement, how I return the id of the inserted row?
Make sure you use LIMIT 1 if you're searching for one specific user.
$stmt = $db->prepare('SELECT * FROM users WHERE user_id = :user_id LIMIT 1');
$stmt->bindValue(':user_id', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_OBJ);
echo $user->user_id;
Here are my solutions :
Put the desired ID of the last SELECT in the $_SESSION['name'].
Put it in the html file as a Hidden Input.
Go fetch it at the beginning of you controller file so it's always set and ready to use.
Use lastInsertId();

Categories