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
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`
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 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 would I add up all the integers in the column, _view_count_, on my table, 'videos', then echo it to display on my page?
For example:
if row id 1 has view_count == 328
and
if row id 2 has view_count == 271
How would I make MySQL add those together and echo it out?
You can use MySQL's SUM() and your SQL query would look something similar to:
SELECT SUM(view_count) FROM videos;
To query and echo the value, if you're using mysqli methods in your PHP code, you can use:
$result = $mysqli->query('SELECT SUM(view_count) AS sum FROM videos;');
$row = $result->fetch_assoc($result);
echo $row['sum'];
Assuming you have a $mysqli object defined your code should look like:
$query = "SELECT Sum(view_count) as mySum FROM videos";
$result = $mysqli->query($query);
$row = $result->fetch_assoc($result);
echo $row['mySum'];
SELECT SUM(view_count) FROM videos
Assuming you have a COLUMN id, you can use SUM together with IN, like so:
SELECT SUM(view_count) FROM videos WHERE id in (1,2)
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