This is the code giving me issue - I'm trying to update multiple records with one insert. The values are put in an array and using a foreach I've prepared the mysqli update. But it's not working. Just gives a MySqli error about the syntax on the update.
foreach($users as $user){
if(empty($course)) continue;
$query_string .= " SET group_id='$group_id' WHERE user_id='".$user."'; ";
}
$query_string = substr($query_string,0,-1);
$query = "UPDATE users" . $query_string;
$result = mysqli_query($dbc, $query) or trigger_error("Query: $query");
The error it gives is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET group_id='10' WHERE user_id='5''. I think it's the ';' in the middle that mysqli isn't accepting.
Assuming you've got more than one user, your query will look like
UPDATE users SET ... SET ... SET ... SET ...
which is incorrect. You cannot do updates to multiple rows in this fashion. Either do multiple queries, each updating one student, or you'll have to build a huge case/if block to do this in a single query.
You'd be better off doing the multiple queries, as you'll probably spend more time BUILDING the monolithic query than it'd take to run the individual updates.
How about WHERE...IN
UPDATE foo SET bar = 0 WHERE baz IN (1,2,3,4,5,6)
(presuming that you are setting them all to the same group ID, which is not clear in the context provided)
try this code:
<?php
$queries = array();
foreach($users as $user){
if(empty($course)) continue;
$queries[] = "update users set group_id = '" . mysql_real_escape_string($group_id) . "' where user_id = '" . mysql_real_escape_string($user) . "'";
}
array_map('mysql_query', $queries);
?>
Your problem is that you don't separate the different users with ;. Since you're updating all users to have the same group (I'm not sure this is the case, otherwise it will get much more complex) you can simply expand the criteria with OR. Your resulting query would look something like the following:
UPDATE users SET group_id='42' WHERE user_id='1' OR user_id='2' OR user_id='3';
Another solution would be to use WHERE ... IN. Here's an example of that:
UPDATE users SET group_id='42' WHERE user_id IN (1, 2, 3);
Related
There are many questions on SO about this but I cannot find one that quite meets my situation.
I want to use the values in some fields/columns of a table to set the value of a third field/column
In other words something like:
table races
athleteid|difficulty|score|adjustedscore
$sqlSelect = "SELECT athleteid,difficulty,score FROM races";
$res = mysql_query($sqlSelect) or die(mysql_error());
while ($row = mysql_fetch_array($res)){
$adjustedscore=difficulty*score;
$sqlupdate = "UPDATE race, set adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
$resupdate = mysql_query($sqlupdate);
}
My understanding, however, is that MYSQL does not support update queries nested in select ones.
Note, I have simplified this slightly. I am actually calculating the score based on a lot of other variables as well--and may join some tables to get other inputs--but this is the basic principal.
Thanks for any suggestions
You can run:
UPDATE `races`
SET `adjustedscore` = `difficulty` * `score`
WHERE `athleteid` IN (1, 2, 3, ...)
First of all, as previous commentators said, you should use PDO instead of mysql_* queries.
Read about PDO here.
When you'll get data from DB with your SELECT query, you'll get array. I recommend you to use fetchAll() from PDO documentation.
So, your goal is to save this data in some variable. Like you did with $row.
After that you'll need to loop over each array and get your data:
foreach($row as $r) {
//We do this to access each of ours athlete data
$adjustedscore= $row[$r]["difficulty"]* $row[$r]["score"];
//Next row is not clear for me...
$query = "UPDATE race SET adjustedscore = '$adjustedscore' WHERE athletes = 'athletes'";
And to update we use PDO update prepared statement
$stmt = $dbh->prepare($query);
$stmt->execute();
}
`$sql = "call geodist(".$_SESSION['This'].",500)";` //get the ids near you
$result=mysqli_query($GLOBALS['link'],$sql) or die(mysqli_error($GLOBALS['link']));
while($row=mysqli_fetch_assoc($result)) // insert them into nerby table
{
$sql = "INSERT INTO `nearby`(`userid`, `strangerid`) VALUES (".$_SESSION['This'].",".$row['id'].")";
mysqli_close($GLOBALS['link']);
mysqli_query($GLOBALS['link'],$sql)
or die("akash".mysqli_error($GLOBALS['link']));
}
when i remove the '//*' statements i get out of sync error.... keeping those two lines help me run my code but code becomes slow since for every loop iteration the database connection is closed and reopened. pls tel me an alternate.... i will really be grateful to you
What happens is you have data in the buffer between mysql and PHP when you try to fill it with new data (the query inside the loop).
What you need to do is
either fetch all data from the buffer before you use it for other query
See how u set this mysqli connection to fetch data unbuffered.
Read more here
http://dev.mysql.com/doc/apis-php/en/apis-php-mysqlinfo.concepts.buffering.html
DROP TEMPORARY TABLE IF EXISTS near;
CREATE TEMPORARY TABLE near
i added these 2 lines in my geodist() procedure.
it creates a temporary table named "near" and stores the result set in it.
now this table could be used as follows
$sql = "call geodist(".$_SESSION['This'].",".$GLOBALS['RADIUS'].")"; // get the ids near you
$result=mysqli_query($GLOBALS['link'],$sql) or die(mysqli_error($GLOBALS['link']));
$sql = "SELECT m.`id`\n"
. " FROM `members` m , `already_assigned` a\n"
. " WHERE a.`id`=m.`id` and m.`id` <> ".$_SESSION['This']."\n"
. " and m.`gender`=".$_SESSION['wants']." and m.`interested_in`=".$_SESSION['gender']." and a.`status`='free'\n"
. " and m.`id` IN (SELECT * from `near`)\n" /*see this line*/
. " ORDER BY RAND( ) \n"
. " LIMIT 1";
you can see that now i have removed the while loop... now its not required
How 'bout not closing the database connection until you're actually done with it?
You should only ever establish ONE connection to any given database server (so basically, one connection in your script unless you're working with a complex multi-DB-server setup)
I am using this database class for my project: GitHub.
When trying to execute a SHOW query to determine whether a table exists or not I receive this error:
Fatal error: Problem preparing query (SHOW TABLES LIKE users) You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'users' at line 1 in mysqli.php on line 679
The query looks like this:
$result = $DATABASE->rawQuery("SHOW TABLES LIKE " . $TABLE);
$TABLE is obviously filled with a string, I double checked that.
Any idea what could be wrong?
You probably missed the quotes:
$result = $DATABASE->rawQuery("SHOW TABLES LIKE '" . $TABLE . "'");
The like statement it's value is wrong.
You should use:
BAD
$result = $DATABASE->rawQuery("SHOW TABLES LIKE 'value here' ");
Good
$result = $DATABASE->rawQuery("SHOW TABLES LIKE ? ");
$DATABASE->addParam($table);
I think you allso want to add % in front and after your $table :)
I am trying to get a value of an int from a field in a MySql database and increment it by 1 when a new record is added. What is happening, is that when the record is inserted it is placing a 1 and not adding one to the value of the field. For example, in the last record, the value is 10 so after running the query the value should be 11.
I am struggling to see why this is not working and would be grateful if someone could offer any advice as to how to amend my code to a working solution. Many thanks
php code
function get_ref(){
$query = "SELECT MAX(`id_usr`) AS `max` FROM `user_usr`";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$max = $row['max'];
$sql = 'select idcom_usr'
. ' from user_usr'
. " where id_usr = '$max'"
. ' order '
. ' by id desc'
. " limit 1";
$result = mysql_query($sql);
$ref = mysql_result($result,0,"idcom_usr");
return $ref + 1;
}
You can have the column auto incrementing. This way you offload the work from PHP to MySQL, which is always a good thing.
Oh yeah, and Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can try to achieve your goal using a trigger
CREATE TRIGGER tg_user_usr_insert
BEFORE INSERT ON user_usr
FOR EACH ROW
SET NEW.idcom_usr = (SELECT COALESCE(MAX(idcom_usr), 0) + 1 FROM user_usr);
Then when you insert new rows
INSERT INTO user_usr (idcom_usr) VALUES (0),(0);
Values for idcom_usr will be assigned by the trigger.
Here is SQLFiddle demo.
Even if for some reason you do it in php instead of two queries you need only one
SELECT COALESCE(MAX(idcom_usr), 0) + 1 next_value
FROM user_usr
Note: this approach is prone to errors under heavy load due to concurrency.
I'm trying to update multiple rows in one table in MySQL database by doing this. And its not working.
$query = "UPDATE cart SET cart_qty='300' WHERE cart_id = '21';
UPDATE cart SET cart_qty='200' WHERE cart_id = '23';
UPDATE cart SET cart_qty='100' WHERE cart_id = '24';";
mysql_query($query,$link);// $link is specified above
Anyone know what is wrong with this.
From the PHP documentation:
mysql_query() sends a unique query (multiple queries are not supported)
The ; separates SQL statements, so you need to separate the queries if you want to continue using the mysql_query function...
mysql_query can't use multiple queries.
The easiest thing is to just run them separately. I believe you can do multi query but I haven't tried it.
$updateArray = array(21=>300,23=>200,24=>100);
foreach($updateArray as $id=>$value)
{
$query = "UPDATE cart SET cart_qty='$value' WHERE cart_id = '$id'";
mysql_query($query,$link);// $link is specified above
}
This will accept a combination of IDs and their corresponding cart value. Looping though, it builds the query and executes it. The array can then come from a variety of sources (results from another query, form inputs or, as in this case, hard-coded values)
Update:
If you really need to execute all in one, heres the PHP info on multi query:
mysqli::multi_query
You can do it this way:
UPDATE table
SET col1 = CASE id
WHEN id1 THEN id1_v1,
WHEN id2 THEN id2_v1
END
col2 = CASE id
WHEN id1 THEN id1_v2,
WHEN id2 THEN id2_v2
END
WHERE id IN (id1, id2)
This example shows updating two different columns in two different rows so you can expand this to more rows and columns by cludging together a query like this. There might be some scaling issues that makes the case statement unsuitable for a very large number of rows.
You'll need to send them as separate queries. Why not add the queries as strings to an array, then iterate through that array sending each query separtely?
Also check this thread for another idea
This isn't the best method.. But if you need to do multiple queries you could use something like...
function multiQuery($sql)
{
$query_arr = explode(';', $sql);
foreach ($query_arr as $query)
{
mysql_query($query);
}
}
another example of a helper query
function build_sql_update($table, $data, $where)
{
$sql = '';
foreach($data as $field => $item)
{
$sql .= "`$table`.`$field` = '".mysql_real_escape_string($item)."',";
}
// remove trailing ,
$sql = rtrim($sql, ',');
return 'UPDATE `' . $table .'` SET '.$sql . ' WHERE ' .$where;
}
echo build_sql_update('cart', array('cart_qty' => 1), 'cart_id=21');