Update the first row mysql php - php

I'm trying to update my first row in my database. I use the Limit 1 to only update the first row but nothing is happening. There are definitely matching rows but nothing changes in the database.
Here is the code:
foreach ($player_fromsite as $match_player_in_game) {
//$querytwo = 'INSERT INTO `'.$tablename.'` '.' (`'.$match_player_in_game.'`) '.'VALUES'.'("' . 'yes' . '")';
$querytwo = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
$querythree = 'UPDATE '.$tablename.' SET `'.$match_player_in_game.'` = "'.'yes'.'" WHERE `'.$match_player_in_game.'` = "'.'NULL'.'" LIMIT 1';
for($a=0;$a<11;$a++){
if($match_player_in_game == $home_players[$a]){
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
}else{
mysql_query($querythree) or die(mysql_error());
}
}
}
Is the query correct?

In MySQL use IS NULL to compare with NULL.
For example: "UPDATE table SET field = 'yes' WHERE field IS NULL"

NULL isn't a string, so you shouldn't be using = 'NULL', unless you actually set it to that string value. Use IS NULL instead.

You need to define "first row". First row based on an autoincrementing id value? First based on a timestamp date? You need to specify this as MySQL has no concept of "first row".
For example, if you do something like this in MySQL:
SELECT * FROM table LIMIT 1
You are not guaranteed to get the same record back each time.
Most likely you will need to specify an ORDER BY condition on a key column, as without it, you have no guarantee of which row your LIMIT 1 will apply to. I really can't think of a case where one might use LIMIT without an ORDER BY clause, as the two really go hand in hand.
So your query should look like:
UPDATE table
SET field = 'yes'
WHERE field IS NULL
ORDER BY some_key_field ASC
LIMIT 1
Note that even this query would not update the same row every time. It would update the first record (as specified by ORDER BY) that has a NULL value for the specified field. So if you ran this query 10 times, it would change 10 different records (assuming there are that many records with NULL values).

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.

How can I use mysqli / php to update all records after a query has already been executed?

I have a user form that sets a single record "current". No more than one record can be set to current at a time. So, I present the user a single drop down list, they choose the item they want to set current and hit "UPDATE" at the bottom of the form.
The PHP/Mysqli needs to go in and set all records column "current" to a value of 0 then update the one from the form to a value of "1".
Initially, I just did a simple count the number of rows, and run a bunch of queries to update the column to 0 or 1 if the loop counter = the id of the row. Well... that broke quick as I started doing testing on other portions and the index numbers got higher than the total number of rows. Yes, dumb way to do it initially!
Here's what I tried to do with the PHP / MySQL code:
// $link is the database link defined elsewhere. This does work as I use it all over the place
$setCurrent = X; // This is the number passed from my form
$init_query = "SELECT id, current FROM myTable";
if ($stmt = $link->$prepare($init_query) {
$stmt->execute() or die ($stmt->error);
$stmt ->bind_result($id, $current)
while ($stmt->fetch()){
if ($id == $setCurrent){
$update_sql = "UPDATE myTable SET current ='1' WHERE id='".$setCurrent."'";
$stmt2 = $link->prepare($update_sql);
$stmt2->execute;
}
else {
$update_sql = "UPDATE myTable SET current ='0' WHERE id='".$id."'";
$stmt2 = $link->prepare($update_sql);
$stmt2->execute;
}
$stmt->close();
This fails and gives me a Fatal error: Uncaught Error: Call to a member function execute on boolean in .....
I am racking my brain over this and can't figure out what the heck is going on. Its been a few years since I have worked in PHP/MySql and this is my first forray into OO Mysqli. Please be gentle :)
You're missing two closing curly braces. One for the first if() and the other for while()
why do them one at a time? You can do it in one query
$setCurrent = X;
$query = 'UPDATE myTable
SET `current` = (id = :current)';
$stmt = $link->prepare($query);
$stmt->bindValue(':current', $setCurrent);
$stmt->execute();
(and misusing the fact that if id equals $setCurrent, the part between ( ) resolves to true, which is 1.)
some explaining:
SELECT 10=10; would give a kind of "TRUE". But as Mysql does not give true, it give 1.
the same goes for:
SELECT 10=20; This is FALSE, so gives you 0.
Now back to your query: you want to get a value 0 for all record for which id not equal to some-number. And you want 1 when equal:
So you have to compare the column id's value to $setCurrent. When they match you get 1 and you put that 1 into the column "current"
And when they don't match, all other cases, then you get a 0 and that 0 goes into the column Current.
And yes, this could also be done as:
UPDATE mytable
SET `current` = CASE id
WHEN $setCurrent THEN 1
ELSE 0
END CASE
or using IF,
But they other syntax is way shorter
edit
backtics are needed around column name, as current is a reserved word

MySQL Determine if Query Run when No Change to DB Fields

I want to determine if this script was run regardless if there was a change to the database.
For Example:
1) If name was previously "Joe" then $rowsAffect returns the 'correct' answer "1".
2) If name was previously "Bob" then $rowsAffect returns the 'INCORRECT' answer "0".
Is there a variable I can use that will tell me the script was run?
$query = "UPDATE table
SET name='Bob'
WHERE id=25";
$result = $link->query($query);
$rowsAffect = mysqli_affected_rows($link);
It you really care about updating rows, then you can add another column, something like LastUpdatedDate:
alter table t add column LastUpdatedDate datetime;
update table t
set name = 'Bob', LastUpdatedDate = now()
where id = 25;
This guarantees that the row is updated, so you will see a row count.
Of course, if you run the query and it doesn't fail, then it really did run.

inserting same query from multiple array

I make a mathematichs function in mysql. and give two result because it`s calculate from 2 records. this is the source :
$calculate= mysql_query("select markers_tujuan.lng,markers_tujuan.lat,open_list.lat, open_list.lng,
((SQRT((((markers_tujuan.lat-markers_tujuan.lng)*(markers_tujuan.lat-markers_tujuan.lng)) + ((open_list.lat-open_list.lng)*(open_list.lat-open_list.lng)))))+(sqrt((((markers_tujuan.lat-open_list.lat)*((markers_tujuan.lat-open_list.lat)))+((markers_tujuan.lng-open_list.lng)*((markers_tujuan.lng-open_list.lng)))))))
as hasil
from markers_tujuan, open_list");
$op=mysql_query("select * from open_list");
$line=mysql_fetch_assoc($op);
/* fetch associative array */
while ($row = mysql_fetch_assoc($calculate)) {
printf ("1(%s %s),(%s %s),%s <br> \n", $row["lng"], $row["lat"], $row["lat"], $row["lng"], $row["hasil"]);
$try=mysql_query(" UPDATE open_list SET hitung = '".$row["hasil"]."' ");
}
and the result is
but I didn`t understand why query in mysql updating same query
As others have pointed out, your UPDATE statement does not have a WHERE condition. Therefore, every single row in your table will be updated, each time:
mysql_query(" UPDATE open_list SET hitung = '".$row["hasil"]."' ");
You should specify the PRIMARY KEY while updating. In this case, it is the column id (I presume). Example:
UPDATE open_list SET hitung = 'example' WHERE id = '4'
You should add SELECT open_list.id,... on your first query and WHERE id = ' . $row['id'] in the update sentence.

How do I fetch the last record in a MySQL database table using PHP?

I want to fetch the last result in MySQL database table using PHP. How would I go about doing this?
I have 2 Columns in the Table, MessageID(auto) & Message.
I already know how to connect to the database.
Use mysql_query:
<?php
$result = mysql_query('SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1') or die('Invalid query: ' . mysql_error());
//print values to screen
while ($row = mysql_fetch_assoc($result)) {
echo $row['messageid'];
echo $row['message'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
The SQL query:
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
...uses the ORDER BY to set the values so the highest value is the first row in the resultset. The LIMIT says that of all those rows, only the first is actually returned in the resultset. Because messageid is auto-increment, the highest value is the most recent one...
Records in a relational database do not have an intrinsic "order" so you cannot fetch the "last" record without some kind of ORDER BY clause.
Therefore, in order to fetch the "last" record, simply reverse the ORDER BY clause (change ASC to DESC or vice versa) then select the first result.
If you have an auto-increment field and you just want to find the last value that was inserted, you can use the fact that the auto-increment fields are ever-increasing (therefore the "last" one will be the one with the highest value) and do something like this:
SELECT *
FROM my_table
ORDER BY id_field DESC
LIMIT 1
Of course you can select the last row by sorting DESC in your query. But what if you want to select the first row and then the last. You can run a new query, but you can also use the function mysql_data_seek. check code below:
$result = mysql_query('YOUR QUERY') or die('Invalid query: ' . mysql_error());
$row_first = mysql_fetch_array($result);
mysql_data_seek($result , (mysql_num_rows($result)-1));
$row_last = mysql_fetch_array($result);
Hope this helps
The MySql query would look like this:
select MessageID, Message
from Table
order by MessageID desc
limit 1;
I am too rusty with PHP to give you the right syntax for executing this.
This query works because you have an auto-incrementing identifying field (MessageID). By ordering the results by that field in descending (largest to smallest) order we are effectively returning the records in the table in reverse order. The limit 1 clause simply limits the result set to one record - the last one in the table.
What do you mean by "the last result"? You need to precise a bit more.
Do you mean "the last entry I registered"?
In this case you should use the appropriate method (depending on the extension you are using) mysqli->insert_id OR mysql_insert_id.
If you mean "the latest entry in the table", an SQL query such as Andrew Hare's is just what you need.
Do you mean the last record or do you need the id of the most recently inserted record? For that you would use the PHP mysql_insert_id() function. Or if you are using the myusqli extension use $mysqli->insert_id.
for some reason (which I don't know why), my boss force me to get the data in this way:
$message_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$message_arr['messageid']= $row['messageid'];
$message_arr['message']= $row['message'];
}
return $message_arr;
Of course, you need everything from OMG Ponies's answer I'm just telling you another way to do it =)
I hope this help.
You should use SELECT query. How SELECT works.
SELECT * FROM table - selects everything in a table (id, row 1, row 2,...)
SELECT id FROM table - selects only particular row from table.
If you now know, how to select, you can use additional logic.
SELECT * FROM table ORDER by id DESC LIMIT 1;
selects everything from table table, orders it by id - orders it DESCENDING and limits the query to only one result.
If you would do it like this:
SELECT * FROM table ORDER by id ASC limit 1; - you would get 1 entry into database.
You can order it by any row you want.
Hope it helps.
One thing to remember is that data does not get saved in the insertion order in any MYSQL database. So in order to get the last entered record u will have to have an auto increment field. Since there is an auto increment field in this table we are good to go.
The below script will help to get the last entered record
<?php
$sql = "SELECT * FROM table_name ORDER BY MessageID DESC LIMIT 2";
$result_set = mysql_query($sql);
if($result_set){
while($row = mysql_fetch_array($result_set)) {
echo "Message Id: ".$row['MessageID']."<br>";
echo "Message: ".$row['Message']."<br>";
}
//creating alert
echo "<script type=\"text/javascript\">alert('Data was Retrieved
successfully');</script>";
}
else{
//creating alert
echo "<script type=\"text/javascript\">alert('ERROR! Could Not Retrieve
Data');</script>";
}
?>
The query selects all the records in the table and orders them according to the descending order of the MessageID (as it is the auto increment field) and limits the returned result to only one record. So since the table is ordered according to the descending order of the MessageID only the last entered record will be returned.
NOTE: if you are using a newer version you will have to use mysqli_query($connection_variable,$sql); instead of mysql_query($sql); and mysqli_fetch_array($result_set) instead of mysql_fetch_array($result_set)
$result = mysql_query('select max(id) from your_table ') or die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo $row['id'];
echo $row['message'];
}
//
//
mysql_free_result($result);
simple like that
this code of php works fine
SELECT t.messageid, t.message
FROM TABLE t
ORDER BY t.messageid DESC
LIMIT 1
if you don't have concurrent entries going into some table.b'cause concurrent entries may not go in accordance of their insertion order.
$statement = $PDO->prepare("
SELECT MessageID,
Message
FROM myTable
ORDER BY MessageID DESC
LIMIT 1;
");
$statement->execute();
$result = $statement->fetch(\PDO::FETCH_ASSOC);
echo $result['MessageID']." and ".$result['Message'];

Categories