MySQL query went wrong - php

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().

Related

MySQL alternative to Read/Modify/Write a field

In several PHP codes I have to just increment a field value from a MySQL DB.
Tipically, I use this snippet:
$sql = "SELECT IDpage, numPages FROM Pages WHERE IDpage=".$page;
$result = mysqli_query( $conn,$sql)
$row = mysqli_fetch_array($result);
$num = $row['numPages'] + 1;
$sql = "UPDATE Pages SET numPages=".$num." WHERE IDpage=".$page;;
$result = mysqli_query( $conn,$sql)
Is there any more elegant and concise method?
You don't need to fetch the data first, just do the update.
$sql = "UPDATE Pages SET numPages = numPages + 1 WHERE IDpage = ".$page;
$result = mysqli_query($conn, $sql);
Also, your snippet is missing a few semicolons.

SELECT gives old values after UPDATE

I get value from the table, change it and update the value in the table. After that I try to select this value from the table, but it gives old value that was before updating. In the phpmyadmin I see that value was changed. I can't see what is wrong.
require_once('conn.php');
$query = "SELECT first FROM vote WHERE id = 1";
$result = mysqli_query($conn, $query);
$value = $result->current_field;
echo $value."<br>";
$newvalue = $value + 1;
echo $newvalue;
$sql = "UPDATE vote SET first = ".$newvalue." WHERE id = 1";
$do = mysqli_query($conn, $sql);
$conn->close();
Try to do like that:
require_once('conn.php');
$query = "SELECT first FROM vote WHERE id = 1";
$result = mysqli_query($conn, $query);
if($result){
if($row = mysqli_fetch_assoc($result){
$value = $row['first'];
echo $value."<br>";
$newvalue = $value + 1;
echo $newvalue;
$sql = "UPDATE vote SET first = $newvalue WHERE id = 1";
$do = mysqli_query($conn, $sql);
$conn->close();
}
}
Try adding a commit after "update" statement.
$sql = "UPDATE vote SET first = ".$newvalue." WHERE id = 1; COMMIT;";
You may want to create a function for commit.
function commit(){
return mysql_query("COMMIT", $this->connection);
}
reference: http://php.net/manual/en/function.mysql-query.php
Also, please provide details about the mysql client version you are using. In newer versions, you can configure autocommit.

MySQL Insert on first table and update on 2nd table

I am trying to insert data into table_1 and then insert on second table if the new inserted ID not available on 2nd table if available then update it. Bellow is my code please tell me what I'm doing wrong.
<?php
$name='Name';
$pass='Passsword';
$rid='FR200000';
$sql = "INSERT INTO table_1 (id,name,pass) VALUES('".$rid."','".$name."','".$pass."')";
$res = mysql_query($sql);
if(!$res){
echo'Failed to insert';
}else{
$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
$res = mysql_query($sql);
$get_id = mysql_fetch_assoc($res);
if (!$get_id==$rid){
$site_url = 'www.example.com';
$site_email ='example#mysite.com';
$sql = "INSERT INTO site_settings (id,site_url,site_email) VALUES('".$rid."','".$site_url."','".$site_email."')";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
if ($get_id==$rid){
$sql = "UPDATE site_settings SET site_url = '" . $site_url . "', site_email = '" . $site_email . "' WHERE ID = '".$rid."'";
$res = mysql_query($sql);
if(!$res) return 1;
return 99;
}
?>
mysql_query()
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning
resultset
$sql = "SELECT id FROM site_settings WHERE id = '".$rid."'";
$get_id = mysql_query($sql);
You will not compare directly result set with $rid
if (!$get_id==$rid){
You need to fetch data first
$row = mysql_fetch_assoc($res);
$get_id=$row['id'];// fetch data
Then compare
if (!$get_id==$rid){
// YOUR code
NOTE:- mysql is deprecated instead use mysqli OR PDO

My MySQLi dosen't update only inserts? What's wrong with my script?

$check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
$user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));
if(mysqli_num_rows($check_verified_user) > 0) {
mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
} else {
mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
}
I don't know what's wrong with my script, it checks if the row exists, then if it exists it should update, but instead it inserts another row, which i don't understand...
Give this a try.
$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);
You basically wasn't giving it the database connection, so it was always coming back as not being greater than 0 rows. Personally, I always put my query into its own variable first, and this will ensure that you don't forget params for the mysqli_query() function. It also makes it easier to read, and allows you to use the query in other places if needed.
You can do this method:
$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
if (mysqli_num_rows($result)) {
$sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
$sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}
mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
If your user_mail is a UNIQUE KEY you would be able to use the option ON DUPLICATE KEY UPDATE in the INSERT. You can do everything in just 1 query.
$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";
mysqli_query($conDB, $sql);
Check this example of a table using UNIQUE KEY.
http://sqlfiddle.com/#!2/4919e2/1/0

sql server update when WHERE exist

I have sql + php query and i need inform user when update fail exmpl:
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
sqlsrv_query( $con, $sql);
And now if php variables values not 100% match values in db update fails but users cant see that. He can check records and try again. I would like inform him when query update nothing.
Like GOB commented, you can use the PHP sqlsrv_rows_affected function to retrieve the number of affected rows. For example:
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_rows_affected( $stmt );
if ($row_count === false)
echo "Error in retrieving row count.";
else
echo $row_count;
Before directly executing update query,check whether condition in update query exists or not. This can be done by selecting count of that condition.
Try below code:
$sql = "select count(*) as count from db WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' ";
while($row = mysqli_fetch_array($sql))
{
$count = $row['count'];
}
if($count == 0)
{
echo 'update will fail';
}
else
{
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
}

Categories