inserting same query from multiple array - php

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.

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.

SELECT in UPDATE in the same table

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

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

Update the first row mysql 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).

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