How to run multiple query on single save button? - php

When I click on the save button only all_university table updates but the all_colleges table has not been updated. How can I update two tables on one save button?
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
$value = mysqli_multi_query($link,$sql);
if($value == true){
$msg .="<h5 style='color:green'>Successfull</h5>";
} else {
$msg .="<h5 style='color:red'>Error!</h5>";
}
}
?>

It doesn't matter how many queries you have. Just run them all one by one.
Besides, you should be using prepared statements.
<?php
if(isset($_POST['save'])) {
$chk = implode(",", $_POST['company_name']);
$sql = "update all_university set placement = ? where university_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['university_name']);
$stmt->execute();
$sql = "update all_colleges set placement = ? where college_name = ?";
$stmt = $link->prepare($sql);
$stmt->bind_param("ss", $chk, $_POST['college_name']);
$stmt->execute();
$msg .="<h5 style='color:green'>Successfull</h5>";
}
DO NOT use mysqli_multi_query(). It will do you no good and won't work the way you think.

If you want to use the multi-query function, you have to concatenate the two query strings:
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
And then execute mysqli_multi_query.
Or, as Rory already mentioned, just query twice using the normal mysqli_query function.
But you should really look into prepared statements as you are vulnerable to SQL injection!

Separate both query with semicolon (;)
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."';";
$sql = "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Then, Append Both Query.
$sql = "update all_university set placement = '$chk' where university_name = '".$_POST['university_name']."'";
$sql .= "update all_colleges set placement = '$chk' where college_name = '".$_POST['college_name']."'";
Execute it.
$value = mysqli_multi_query($link,$sql);
The mysqli_multi_query() function performs one or more queries against
the database. The queries are separated with a semicolon.

Related

How to save variable as a string in database?

I am trying to save a string with number and math operator into database. I want to save the face value of string, but php or mysql is calculating the string and then saving it to the database.
For example:
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value =".$stringValue;
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
After running the code, I want the value saved in database to be "24/2", but it is being saved as 12.
As #Uueerdo said you need to add ' sign before and after string in SQL.
$stringValue = "24/2";
$query = "UPDATE winter";
$query .= " SET value ='".$stringValue."'";
$query .= " WHERE name = 'xyz'";
$result = mysqli_query($connection, $query);
Also you probably should use prepared statements (not much longer, but more safer).
$stringValue = "24/2";
$name = "xyz";
$query = "UPDATE winter";
$query .= " SET value=?";
$query .= " WHERE name=?";
$stmt = $connection->prepare( $query );
$stmt->bind_param( 'ss', $stringValue, $name );
$stmt->execute();
$res = $stmt->get_result();

MySQL query went wrong

can you say me where are i am making mistakes in this simple query
$q = "UPDATE users SET ".$aItemSlot." = '$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
error-
1064 - 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 ''$aItemSlot' = '$seton' WHERE username='$us'' at line 1
Here is my source
$q = "SELECT * FROM users WHERE username='$us'";
$r = #mysqli_query($dbc, $r);
$row = mysqli_fetch_array($r);
$aHelmet_Slot = $row['helmet_slot'];
$aShield_Slot = $row['shield_slot'];
$aWeapon_Slot = $row['weapon_slot'];
$aGloves_Slot = $row['g1loves_slot'];
$aShoes_Slot = $row['shoes_slot'];
$aArmor_Slot = $row['armor_slot'];
$aEar_Slot = $row['ear_slot'];
$aBelt_Slot = $row['belt_slot'];
$aRing1_Slot = $row['ring1_slot'];
$aRing2_Slot = $row['ring2_slot'];
$aRing3_Slot = $row['ring3_slot'];
$aRing4_Slot = $row['ring4_slot'];
$aCharLevel = $row['char_lvl'];
if ($aItemSlot == 'ring_slot'){
if($aCharLevel >= $aItem_Level){
$NotEmpty = false;
if ($aRing1_Slot == 0){
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing2_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring2_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if (($aRing3_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring3_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(($aRing4_Slot == 0) && (!$NotEmpty)){
$q = "UPDATE users SET ring4_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
if(!$NotEmpty){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aRing1_Slot'";
$r = #mysqli_query($dbc, $q);
$q = "UPDATE users SET ring1_slot='$seton' WHERE username='$us'";
$r = #mysqli_query($dbc, $q);
$NotEmpty = true;
}
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
else
{
if ($aCharLevel >= $aItem_Level){
$link_slot_var = "a" .$aItemSlot;
$aSlotItemID = $$link_slot_var;
if($aSlotItemID <> 0){
$q = "UPDATE items SET item_position='2' WHERE it_id='$aSlotItemID'";
$r = #mysqli_query($dbc, $q);
}
$q = "UPDATE users SET '$aItemSlot' = '.$seton.' WHERE username='$us'; // it fails there
$r = #mysqli_query($dbc, $q);
$q = "UPDATE items SET item_position='3' WHERE it_id='$seton'";
$r = #mysqli_query($dbc, $q);
}
}
There Should not be a $ symbol before the mysql database field name it should be something like this
UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'
Modify your query in the above format and try to execute
Why do you use a table name as variable?
{$aItemSlot}
In general it should be like this:
$mysqli->query("Update users
set aItemSlot = '$seton'
where username = $us
") ;
Also, try to use prepared statements.
UPDATE
Make update of the row which related to this table:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
UPDATE statement updates columns of existing rows in the named table
with new values. The SET clause indicates which columns to modify and
the values they should be given. Each value can be given as an
expression, or the keyword DEFAULT to set a column explicitly to its
default value. The WHERE clause, if given, specifies the conditions
that identify which rows to update. With no WHERE clause, all rows are
updated. If the ORDER BY clause is specified, the rows are updated in
the order that is specified. The LIMIT clause places a limit on the
number of rows that can be updated.
You can also perform UPDATE operations covering multiple tables.
UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;
UPDATE2
You need to check/update each row.
$stmt = $mysqli->prepare("UPDATE table SET col1 = ?, col2 = ?, col3 = ? WHERE id = ? ")
$stmt->bind_param('sssi', $var1, $var2, $var3, $id);
This shows what you need to do.
You missed assignment operator :
UPDATE users SET " . $aItemSlot . " = '" . $seton . "' WHERE username='$us'";
Your query should be like this:
"UPDATE users SET " . $aItemSlot . "='$seton' WHERE username='$us'";
^ assignment operator
This is a valid syntax.. how ever you have to be sure that those params are VALID before making the query...
$sql = "UPDATE users SET {$aItemSlot} = '{$seton}' WHERE username = '{$us}'";
Try this, this will surely work
$q = "UPDATE users SET ".$aItemSlot." = " . $seton . " WHERE username= " . $us;
You will need to make some slight adjustments.
PHP/SQL
$q = "UPDATE users SET aItemSlot = '".$seton."' WHERE username='".$us."'";
// Or if $aItemSlot actually is a variable
$q = "UPDATE users SET '".$aItemSlot."'='".$seton."' WHERE username='".$us."'";
Bottom note: because $aItemSlot starts with an 'a' I am wondering if this is an array. In that case your script will fail saying that the array to string conversion has failed. If this is the case, check what value $aItemSlot holds using var_dump().

Executing Multiple or Three Queries at Once

I'm currently creating an online reservation system.
How can I execute multiple queries at once?
I'm already using mysqli_muti_query. I have three queries to execute.
<?php
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' "; ?>
You need to Add semicolon after each statement:
<?php
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ;";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' ;";
If supported by your database, I'd suggest that you run your queries separately and wrap them into a single transaction.
$conn->begin_transaction();
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$conn->query($sql);
$sql = "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye';";
$conn->query($sql);
$sql = "UPDATE vehicles set status = '$un' WHERE plateno = '$plate';";
$conn->query($sql);
$conn->commit();
I'd also suggest that you use prepared statements with parameters rather than including values directly into your query string.
You can use PHP mysqli_multi_query-function.
$sql = "INSERT INTO db (name,picuploc,lname,pnumber,age,email,address,city,zipcode,ticketid,pickuptime,dropofftime,dropoffloc,vehicle,plateno,totalprice,date_registered) VALUES ('$first','$pickuploc','$lname','$pnumber','$age','$email','$address','$city','$zip','$ticket','$pickup','$dropoff','$dropoffloc','$car','$plate','$all', NOW());";
$sql .= "UPDATE vehicles set quantity = quantity - $age WHERE vehicle = '$car' AND parent = '$ye' ;";
$sql .= "UPDATE vehicles set status = '$un' WHERE plateno = '$plate' ;";
/* execute multi query */
if ($mysqli->multi_query($query)) {
}

Update multiple rows using for loop and array php

I have this code:
$id1=array($aa1,$aa2,$aa3,$aa4,$aa5,$aa6,$aa7);
$rank1=array($a1,$a4,$a7,$a10,$a13,$a16,$a19);
require_once("connection.php");
for($i=0;$i<7;$i++){
$sql = "update live_tracking set swim_rank = '"$rank1[$i]."' where id = '".$id1[$i]."'";
}
I want to update multiple rows of my mysql database but using the code above only the first index is being updated. Any suggestions?
You can execute one query only by using this :
$sql = "update live_tracking set swim_rank = '".$rank1[$i]."' WHERE id IN (";
for($i=0;$i<7;$i++){
$sql .= $id1[$i].",";
}
$sql .= ")";
$query = mysql_query($sql) or die("error : ".mysql_error());
if($query){
echo "success";
}
Execute the query within the loop itself.
for($i=0;$i<7;$i++)
{
mysql_query("update live_tracking set swim_rank = '".$rank1[$i]."' where id = '".$id1[$i]."'");
}
I can see an error in the sql
$sql = "update live_tracking set swim_rank = '"$rank1[$i]."' where id = '".$id1[$i]."'";
The above should be
$sql = "update live_tracking set swim_rank = '".$rank1[$i]."' where id = '".$id1[$i]."'";
You were missing . in '".$rank1[$i]."'
It seems that you are on right track. but you need to execute query in the loop. like this:
$id1=array($aa1,$aa2,$aa3,$aa4,$aa5,$aa6,$aa7);
$rank1=array($a1,$a4,$a7,$a10,$a13,$a16,$a19);
require_once("connection.php");
for($i=0;$i<7;$i++){
$sql = "update live_tracking set swim_rank = '".$rank1[$i]."' where id = '".$id1[$i]."'";
if(!mysql_query($sql)){
echo "not updated".$id1[$i]; exit();
}
}

how to prevent updating more than 1 fields in database

I'm trying to edit data(stored in DB). This is display.php. First it displays data from DB (if no data then blank fields). Then edit button to edit DB.
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
And in edit.php
i simply update the DB. But what if i want to change only 1 field.(problem is all fields gets updated).Here's edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
this query means:
update table user
for each row in this table where u_id = [some value]
set fields C and S and T to some other distinct values
so, your query updates 3 fields at one time, and it is ok, as it what it should do
if you want to change this logic, to update only some fields you need to change query and arguments, for example if you want to change only c use:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
for c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
if you don't know exactly how many arguments will be, you need dynamic query building, like:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
That means that WHERE clause of the request doesn't work. Check if you passing a quotation marks " in you variable $t so you close $sql before WHERE clause

Categories