I've done some research and figured out that it's not possible to do through one query, but instead could for example be done through a transaction. But I can't get the SQL query to work properly. If I use the statements one by one they work all good.
What should I do?
The goal is to update two tables with information from one form.
$query = "
START TRANSACTION;
UPDATE projects
SET
projects.project_name = '".$mysqli->real_escape_string($_POST['project_name'])."',
projects.project_group = '".$mysqli->real_escape_string($_POST['project_group'])."',
projects.project_notes = '".$mysqli->real_escape_string($_POST['project_notes'])."',
projects.project_created = '".$mysqli->real_escape_string($_POST['project_created'])."',
projects.project_start = '".$mysqli->real_escape_string($_POST['project_start'])."',
projects.project_delivery = '".$mysqli->real_escape_string($_POST['project_delivery'])."',
projects.project_orderdetails = '".$mysqli->real_escape_string($_POST['project_orderdetails'])."',
projects.project_owner = '".$mysqli->real_escape_string($_POST['project_owner'])."'
where projects.project_id = '".$mysqli->real_escape_string($_REQUEST['id'])."';
INSERT INTO hours
hours.userhours_id = '".$mysqli->real_escape_string($_POST['project_owner'])."',
hours.projecthours_id = '".$mysqli->real_escape_string($_REQUEST['id'])."',
hours.user_hours = '".$mysqli->real_escape_string($_POST['user_hours'])."'
where projects.project_id = '".$mysqli->real_escape_string($_REQUEST['id'])."';
COMMIT;
";
Mysqli has methods for working with transactions, for example http://php.net/manual/en/mysqli.begin-transaction.php.
Code can be:
$mysqli->begin_tansaction();
$mysqli->query('query1');
$mysqli->query('query2');
$mysqli->commit();
Related
I'm trying to update two tables at the same time. The action completes successfully.However, it updates all records in the the table instead of the ones specified. I have tried the suggestions here, but to no avail. Any ideas what the issue might be? My code looks like below.
$sql = "UPDATE $receiverTable, $currUserTable
SET $currUserTable.originator = '$curr_username',
$receiverTable.originator = '$curr_username',
$currUserTable.status = '$currValue',
$receiverTable.status = '$currValue'
WHERE ($receiverTable.username = '$curr_username')
OR ($currUserTable.username = '$curr_username')";
You have no condition on your JOIN (you really shouldn't be writing JOINs with commas any more) and so every row gets JOINed to every other row, which means that they all have a JOIN to a row in which one of the WHERE conditions is true, hence they all get updated. Rewrite your JOIN with the appropriate condition and the problem will go away. Something like:
UPDATE $receiverTable
JOIN $currUserTable ON $currUserTable.somecolumn = $receiverTable.somecolumn
SET $currUserTable.originator = '$curr_username',
$receiverTable.originator = '$curr_username',
$currUserTable.status = '$currValue',
$receiverTable.status = '$currValue'
WHERE ($receiverTable.username = '$curr_username')
OR ($currUserTable.username = '$curr_username')
If there is no way that the tables can be JOINed, you will need to write the UPDATE as two separate queries.
Instead of doing this with a single update use a transaction to wrap two update commands, something like this.
BEGIN TRANSACTIONS;
UPDATE TABLE1
SET Col1 = 'SomeValue'
WHERE Cond1 = 'SomeCond';
UPDATE TABLE2
SET Col2 = 'SomeValue'
WHERE Cond2 = 'SomeCond';
COMMIT;
UPDATE
Following this I believe with phpi it would look like:
mysqli_autocommit($dbConnection, false);
$query1 = " UPDATE $receiverTable set originator = '$curr_username',
status = '$currValue' WHERE username = '$curr_username' "
$query2 = " UPDATE $currUserTable set originator = '$curr_username',
status = '$currValue' WHERE username = '$curr_username' "
mysqli_query($dbConnection, $query1);
mysqli_query($dbConnection, $query2);
mysqli_commit($dbConnection);
$update = ("UPDATE branch, custodian, atm_machine_list, computer_list
SET branch.branch_name = '$branch_name',
custodian.branch_name = '$branch_name',
atm_machine_list.branch_name = '$branch_name',
computer_list.branch_name = '$branch_name',
branch.branch_code = '$branch_code',
branch.branch_address = '$branch_address',
branch.manager = '$manager',
branch.contact = '$contact'
WHERE branch.branch_name LIKE '%$edit_id%'
AND custodian.branch_name LIKE '%$edit_id%'
AND atm_machine_list.branch_name LIKE '%$edit_id%'
AND computer_list.branch_name LIKE '%$edit_id%'");
I am trying to update multiple tables (branch, custodian, atm_machine_list, computer_list)
I want my query to still update even if some of the table are empty.
for example there is a branch_name from custodian and no branch name on atm_machine_list then it will still update disregarding atm_machine_list but updating custodian at the same time.
Hope someone will help me.
Thanks
I am trying to loop through an array ($lineup_selected) that corresponds to a player row in a database. For each player I would like to execute an UPDATE query to the database that adds the value of $submissions_selected to the total_picks column. I am struggling with the code as it fails to execute the query. Any help please?!
// Select team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
// Loop through and update total_picks for each player in database present in lineup_selected array
$player_picks_query = "SELECT full_name, total_picks FROM table WHERE team=$team_selected";
$result = mysqli_query($conn, $player_picks_query);
while($row = mysqli_fetch_assoc($result)) {
$player = mysql_real_escape_string($row["full_name"]);
$add_player_picks = "UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name = '$player'";
}
why not:
UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE team = '$team_selected'
this way you have only one query to execute and let your database do the looping. Else you would first select some records and then have your database update each one of them to update the record.
I assume the fullname is unique. If not, it would mean your version can have the update-query modify multiple records each time and so my approach is invalid
-- and I seem to repeat a lot of the comments when stating to sanitize and escape your input to be save(r).
edit:
combined it should come to:
// set team & formation
$team_selected = "team1";
$lineup_selected = array("player1", "player2", "player3");
$submissions_selected = 4000;
$updatequery = "UPDATE table
SET total_picks = total_picks + ?
WHERE team= ?";
$stmt = mysqli_prepare($updatequery);
mysqli_stmt_bind_param($stmt, "is", $submissions_selected, $team_selected);
/* execute prepared statement */
mysqli_stmt_execute($stmt);
Myself I am more into the pdo approach, but syntax should be like this.
In your select request you have a team that is obviously a String. So, maybe you can try your request like : "SELECT full_name, total_picks FROM table WHERE team='$team_selected'"
I don't know if PHP is smart enough to put the quotes.
I think it will be better if you use only an update statement.
First of all you implode your array
$lineup_selected = array("player1", "player2", "player3");
$players='".implode("','",$lineup_selected )."';
Now you can update the table
$updateStmt="UPDATE table
SET total_picks = total_picks + $submissions_selected
WHERE full_name in (".$players.") and team=".$team_selected.";
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();
}
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');