I could swear that I had this working last week, but now I get errors.
In PHP I have a large CSV file that I run through a foreach loop and in this loop I have a created a variable that adds an UPDATE line to itself, like this:
foreach ($csv->data as $value){
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]';";
}
mysql_query("$updater") or die(mysql_error());
The CSV file contains over 3000 lines so having the mysql_query() inside the loop obviously makes the process slow and is not recommendable.
Can anyone tell me if I'm missing something or just doing it wrong?
We will temporarily ignore the fact that you are using a PHP extension mysql_ that has been deprecated ( Scheduled for removal from the language) for a number of years now.
For some reason you are adding to the sql query each time through the loop by using the .= syntax. I assume you thought you could run more than one query at a time using the mysql_ extension, but you cannot.
So try this :-
foreach ($csv->data as $value){
$updater = "UPDATE tblProduktData SET xtra = 2 WHERE id = '$value[1]'";
mysql_query($updater) or die(mysql_error());
}
This is in fact a perfect candidate for using mysqli_ or PDO prepared statements.
The mysqli_ extension manual
The PDO manual
Try this:
$id = "0"; // initialze the ids to update with a non-existing value
// fetch all the ids into a variable
foreach ($csv->data as $value){
$id .= "," . $value[1]
}
$updater .= "UPDATE tblProduktData SET xtra = 2 WHERE id in (".$id.") ;";
mysql_query("$updater") or die(mysql_error());
Related
I want to have the fields names separated with ',' .
This query
show COLUMNS FROM ma_table;
Returns raw unseparated values
$sql = "show COLUMNS from ma_table ";
$req = mysql_query($sql) or die('Erreur<br>'.$sql.'<br>'.mysql_error());
while ($rslt = mysql_fetch_assoc($req)) {
$fields=$rslt['Field'];
}
mysql_close();
All you need to do is concatenate a comma onto $fields as you process round the while loop.
You also need to use the .= string concatenation operator in the loop so you are adding each new Field to the string and not overwriting it each time.
$fields = '';
while ($rslt = mysql_fetch_assoc($req)) {
$fields .= $rslt['Field'] . ',';
}
echo rtrim($fields, ',');
I am afraid I must also add
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
I have a table of data where I update multiple rows in one transaction. The Foreach loop below works perfectly, however if the table contains a large number of rows there is a fair delay, presumably while the whole table is worked through line by line.
Even if I only change one field in one line, there is a significant delay (20 seconds), which again I am assuming is because the loop is working through each line.
//get data from form
$id2 = $_POST['id2'];
$status2 = $_POST['status2'];
$comment = $_POST['comments2'];
foreach ($id2 as $key2 => $value2){
$query3 = "UPDATE newthing SET comments='$comment[$key2]' WHERE id = $value2 ";
$query4 = "UPDATE newthing SET status='$status2[$key2]' WHERE id = $value2 ";
//execute query
mysql_query($query3);
mysql_query($query4);
}
Is there a more efficient way of undertaking this task? I am open to learning as required if there is a java / ajax / any other sort of tool to use. Additionally, I am aware that mysql_query is old now, so if there's a PDO method of doing this, so much the better. I haven't got my head around PDO at all yet :-/
Many thanks,
Jason
Start by merging into a single update:
foreach ($id2 as $key2 => $value2){
$query3 = "UPDATE newthing SET comments='$comment[$key2]', status='$status2[$key2]' WHERE id = $value2 ";
//execute query
mysql_query($query3);
}
Then start learning about prepared statements/bind variables with the MySQLi or PDO extensions to replace the deprecated MySQL extension, and to help prevent SQL injection
I have a problem. I have an array of values from database, when I try to pass it to a string with commas, it works fine on my localhost, but when I upload it to my online server, the string doesn't show any values. For example: select from table where in (,,) only shows the commas and in my xampp server it works excellent. Any ideas what this can be?
Here's the code:
<?php
$sql = "select id from users where gid = 1";
$result = mysql_query( $sql);
$cat_titles=array();
while( $row=mysql_fetch_assoc($result) )
{
$cat_titles[] = $row['id '];
// do stuff with other column
// data if we want
}
mysql_free_result( $result );
echo "<p>\n";
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
echo "</p>\n";
$cat_titles = implode(',',$cat_titles);
$cat_titles = substr($cat_titles,0,-2);
echo $cat_titles;
echo "select * from users where IN (".$cat_titles.")";
?>
A number of potential issues here:
You are not handling error conditions around you database access, so if you are having issue with your queries you would never know.
Your second select query doesn't specify a field in the WHERE clause, so it will never work
This section of code does absolutely nothing and is in fact where you problem likely lies.
foreach($cat_titles as $v)
{
$cat_titles[]= $row['id'];
}
Here $row['id'] won't have a value, so you are basically looping throguh your existing array and appending empty value to new indexes.
In all likelihood you could do this with a single query, it might help if you explain what you are actually trying to do.
You should not be using mysql_* functions. They are deprecated. Use mysqli or PDO instead.
I have a list of IDs generated from a set of checkboxes as follows:
$list = mysql_real_escape_string(implode(',',$_POST['checkbox']));
which outputs a list like this:
a,b,c
I want to set a column in a MYSQL database that corresponds to each list item, I am unsuccessfully trying to create a query with a foreach loop like so:
$update_query= '';
foreach($list as $item){ //error on this line
$update_query .= "
INSERT INTO t (Col_1, Col_2)
VALUES ('".$item."',now());
";}
It fails telling me I have supplied an invalid argument for foreach(), but I'm not sure, a. what that means, and b. how to fix it; can anyone offer any guidance to get my loop working or a better way of doing this INSERT.
Thanks
$list is a string, not an array. Try passing in the array before you have imploaded it:
$update_query= '';
foreach($_POST['checkbox'] as $item)
{
$update_query .= "INSERT INTO t (Col_1, Col_2) VALUES ('".addslashes($item)."', now());";
}
You'd be much better off using prepared statements, though!
Assuming that the mysqli object is already instantiatied (and connected) with the global variable $mysql, here is the code I am trying to work with.
class Listing {
private $mysql;
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
return $info;
}
}
there are several hundred listings in the db and when I call $result->fetch_array() it places in an array the first row in the db.
however when I try to call the object, I can't seem to access more than the first row.
for instance:
$listing_row = new Listing;
while ($listing = $listing_row->getListingInfo()) {
echo $listing[0];
}
this outputs an infinite loop of the same row in the db. Why does it not advance to the next row?
if I move the code:
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
if I move this outside the class, it works exactly as expected outputting a row at a time while looping through the while statement.
Is there a way to write this so that I can keep the fetch_array() call in the class and still loop through the records?
Your object is fundamentally flawed - it's re-running the query every time you call the getListingInfo() method. As well, mysql_fetch_array() does not fetch the entire result set, it only fetches the next row, so your method boils down to:
run query
fetch first row
process first row
return first row
Each call to the object creates a new query, a new result set, and therefore will never be able to fetch the 2nd, 3rd, etc... rows.
Unless your data set is "huge" (ie: bigger than you want to/can set the PHP memory_limit), there's no reason to NOT fetch the entire set and process it all in one go, as shown in Jacob's answer above.
as a side note, the use of stripslashes makes me wonder if your PHP installation has magic_quotes_gpc enabled. This functionality has been long deprecrated and will be removed from PHP whenever v6.0 comes out. If your code runs as is on such an installation, it may trash legitimate escaping in the data. As well, it's generally a poor idea to store encoded/escaped data in the database. The DB should contain a "virgin" copy of the data, and you then process it (escape, quote, etc...) as needed at the point you need the processed version.