Im trying to update a value in a table, using while loop, but i want this value to be like using auto_inc key.
My table: ID / CAR_ID / IMG_KEY / IMAGE
i want to take 12 rows of the same CAR_ID and give the IMG_KEY values from 1-12.
I tried the below loops, but the result is giving the IMG_KEY the value 1
$getImages = mysql_query("SELECT * FROM more_images WHERE car_id = '$car_id'") or die(mysql_error());
$img_key = 0;
for ($img_key = 1; $img_key <= mysql_num_rows($getImages); $img_key ++) {
while ($selectedImages = mysql_fetch_assoc($getImages)) {
$update = mysql_query("UPDATE `more_images` SET `img_key` = '$img_key' WHERE `car_id` = '$car_id'") or die(mysql_error());
}
}
The goal is give to the following 12 rows img_key values from 1 to 12 and all the other values as they are.
Ok, I'm still not 100% sure what you want, but my guess is that you are looking for something like this:
$imgKey = 0;
while ($selectedImages = mysql_fetch_assoc($getImages))
{
$imgKey++;
$update = mysql_query("UPDATE `more_images` SET `img_key` = '{$imgKey}' WHERE `car_id` = '{$car_id}'") or die(mysql_error());
}
In your question, your for loop isn't doing anything other than looping, in your case it iterates twelve times.
Since mysql_fetch_assoc($getImages) is a function that loops through all rows in a set of results. So for each iteration of your for loop, it updates all records to have the same $img_key.
Also, really do refrain from using mysql_* functions, they're deprecated. Read this thread:
Why shouldn't I use mysql_* functions in PHP?
Related
I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}
I have a SQL-statement like this:
$stmtTHIS = $db->query("SELECT titel, done_date FROM task WHERE project = $tID ");
How can I find out how many rows have an content in "done_date"?
First you have to define what "have content" means then just write a WHERE clause to find those. And use the COUNT function to count the number of rows returned. So lets say "have content" means the field is not null.
SELECT COUNT(*) FROM task WHERE project = $tID AND done_date IS NOT NULL
This counts all the records with that project id and have a value for done_date.
You may also want to check that done_date does not have some other empty value like empty string or 0.
AND done_date != "" AND done_date !=0
Alternate:
Use the query you have to get all those rows, then do the count in PHP:
$stmtTHIS = $db->query("SELECT titel, done_date FROM task WHERE project = $tID ");
$count = 0;
while($row = $stmtTHIS->fetchAssoc()){
//You probably want to do other stiff with the data
if( !empty($row['done_date']) ){
$count++;
}
}
echo $count;
Your code might be slightly different depending on the DB library your using, (I assumed mysqli)
I have to update the same value of multiple rows in a table and i would like to avoid multiple mysql_query using a foreach loop that scan every value of an array.
I try to explain using an example.
This is the solution of the problem using a foreach loop
$array=array(1,2,3);
foreach($array as $val){
$sql = "UPDATE mytable SET val_to_update = XX WHERE id = $val";
mysql_query($sql);
}
I didn't like to start hammering database with a crazy number of queries, because the number of element of the array is not fixed, and can also be large.
I have considered using the IN clause of SQL language but without knowing the number of parameters can not seem to find a solution.
Thinked at something like this, but I do not know if it is achievable:
$sql= "UPDATE Illustration SET polyptychID = $id_polyptych WHERE illustrationID IN (?,?,?);
and then bind all the parameters using a foreach loop for scan the array of parameters.
The problem, as I said, is that i don't know the number, so i can't place the right number of ? in sql query and, if I'm not mistaken, the number of occurrences of ? parameters must be the same as the binded parameters.
Anyone have solved a problem like this?
If you are sure, that the array is containing integers, why don't you do it like this:
$array=array(1,2,3);
if (sizeof($array) > 0 {
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $array).")";
mysql_query($sql);
}
If you want to use prepared statement you could create your sql using this code:
$array=array(1,2,3);
if (sizeof($array) > 0 {
$placeholders = array();
for($i=0; $i<sizeof($array); $i++) {
$placeholders[] = '?';
}
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN(".implode(',', $placeholders).")";
// .....
}
If the values in the $array exists in another table you could use something like this:
$sql = "UPDATE mytable SET val_to_update = XX WHERE id IN (SELECT id FROM another_table WHERE condition = 1)";
I'm trying to make a quick lil' script to just add some dummy data to a new column I added to a database table I have, the table has 1000 entries so doing it by hand isn't really an option.
What I have right now it:
<?php
$conn = mysql_connect('localhost', 'root', ''); mysql_select_db('cdb', $conn);
$string = "4050605040302030405060708070304050403040506070605040302010203040506070655545352515756535243515353545"; //50 values
$mpgsplit = str_split($string, 2);
for ($i=0; $i<=20; $i++)
{
for ($x=0; $x<=50; $x++)
{$r = mysql_query ("UPDATE cars SET mpg = '".$mpgsplit[$x]."'", $conn);}
}
?>
Issue being using update doesn't work as it just replaces the value of every row of that column with each number every time it loops. For me it reached number 48 in the array and timed out.
Then using insert just makes all new rows.
So I need a way to cycle through each row and update it.
The nearest I've been to looping through and dealing with singular rows of a table is this:
$result = mysql_query("SELECT * FROM imported_orders");
$orderNo = $_POST['orderNo'];
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($orderNo>0&&$orderNo<=count($row))
{
$file = fopen('Order.txt', 'w');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
But thats just taking the row as a variable, not sure if I can translate that to what I need.
Theres probably a simple function out there which does this, but I've tried searching and can't find it. Theres also probably an easier way to achieve what I'm trying to do overall as well, so that would be welcome.
All help much appreciated. -Tom
Issue this sql statement directly in mysql command line or from a php script.
SET #r := 0;
UPDATE cars
SET mpg = (#r := #r + 1)
ORDER BY
RAND()
This sql statement will assign number from 0 till Total row count of your db to a random row. I guess it might be helpful
I have some mysql tables (one for each container) like so (the table would be called containerA for instance):
Box_ID Box_Name Box_Distributor Container Box_state
======---========---===============---==========----=========
1 Box 1 Delivery Comp.1 ContainerA Full
2 Box 2 Delivery Comp.2 ContainerA Empty
3 Box 3 NULL ContainerA Missing
and I have another mysql table with a list of containers:
container_id container_name
============---==============
1 A
2 B
and I want to report the name of the container and the number of empty boxes to a webpage.
I've written this to do it:
$v1 = 0;
$sql = "select * from containers";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$containers[] = $row[container_name];
$containerid[] = $row[container_id];
}
while ($v1 < 14)
{
$containerend = $containers[$v1];
$containerstart = "container";
$containername = $containerstart.$containerend;
$sql = "SELECT COUNT(*) FROM `$containername` WHERE state = 'Empty';";
$result = mysql_query($sql) or die(mysql_error());
$count = mysql_fetch_array($result);
var_dump($containers[$v1]);
var_dump($count[$v1]);
$v2 = $v1 + 1;
$v1 = $v2;
}
Which works in listing the container names, but it only gives me the first result for the empty boxes, the rest of the array is returned as NULL:
string(1) "4" NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
Am I doing something stupid here? Surely the SQL query in the while loop should be returning the count for each container?
Any help is appreciated.
change this
while ($row = mysql_fetch_array($result))
{
$containers[] = $row[container_name];
$containerid[] = $row[container_id];
}
to
while ($row = mysql_fetch_array($result))
{
$containers[] = $row['container_name'];
$containerid[] = $row['container_id'];
}
you missed '.
Am I doing something stupid here?
Yes.
Splitting the same data across multiple tables is really dumb.
$sql = "select * from containers";
...
while ($v1 < 14)
{
...
$sql = "SELECT COUNT(*) FROM `$containername` WHERE state = 'Empty';";
Relational database management systems are very good at performing joins. Procedural / OO languages are NOT.
If all your containerX tables where in a single table then the performance would be a lot better and the code much simpler. And it's trivial to create views named like the individual tables on an aggregated table thus avoiding having to rewrite most of your code straight away.
Why are you fetching all the containers then only processing the first 14?
What is $v2 doing?
It's rather hard to work out why your code is misbehaving as your description doesn't match your code - your query states "WHERE state = 'Empty'" but your table description has no column named state (and if that were an accurate report, then the code would stop on the first iteration with a MySQL error message).
$count is in essence only a single value (as you are counting a single container), so it will work for the first element, but not for subsequent elements. Quick fix is to use mysql_result:
$count = mysql_result($result, 0);
as ever, this code is using mysql functions that are both insecure and due to be deprecated - do consider switching to mysqli or pdo.