MySQL alternative to Read/Modify/Write a field - php

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.

Related

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

Display single column value of mysqli query

How can I get a single column value from mysqli? The result should be single row with only one column.
This is what I have tried:
$query = "SELECT MAX(`userid`) FROM `user`";
$rlt = mysqli_query($this->db, $query);
echo $rlt['userid'];
You are not fetching the row after executing the query:
$query = "SELECT MAX(`userid`) FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_row($this->db, $rlt);
echo $row[0];
The alternative would be to use an alias for the computed field and use fetch_assoc:
$query = "SELECT MAX(`userid`) as `maxid` FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['maxid'];
try with create alias and fetch result after query execution also your quote of user' looking wrong
$query = "SELECT MAX(`userid`) as userid FROM `user`";
$rlt = mysqli_query($this->db,$query);
$r = mysqli_fetch_assoc($rlt);
echo $r['userid'];
or fetch only one row like:-
$r = mysqli_fetch_row($this->db, $rlt);
echo $r[0];
You should create alias here.
Use this one:
$query = "SELECT MAX(`userid`) as Max_Userid FROM `user'";
$rlt = mysqli_query($this->db,$query);
$row = mysqli_fetch_assoc($this->db, $rlt);
echo $row['Max_Userid'];
Note: Always use alias when you use mysql function in query with fields.

Cant figure out this mysql to mysqli change

Hi there Im still trying to change to mysqli, and I just can get things to go right some times.
The biggest thing I have is the mysqli_result, ive tried what other people have done, and doesnt seem to work.
Here is the code below:
$result = mysqli_query($con, "SELECT referer FROM users WHERE userId = '$key'");
if(mysql_result($result, 0) != "" ){
$referer = mysql_result($result, 0);
$result = mysqli_query($con, "SELECT referer FROM users WHERE userId = $referer'");
if(mysql_result($result, 0) != "" ){
$result2 = mysqli_query($con, "SELECT refered FROM users WHERE userId = $referer'");
$newRefs = mysql_result($result2, 0) + 1;
mysqli_query($con, "UPDATE users SET refered = '$newRefs' WHERE userId = '$referer'");
$result3 = mysqli_query($con, "SELECT userName FROM users WHERE userId = '$key'");
$refered = mysql_result($result3, 0);
}
}
Help would be appreciated.
Kind Regards
Chad
You can't mix mysql_ and mysqli_ functions like that. Also, mysql_result is serious old school. There is no equivalent in mysqli (and that's a good thing). I switched to mysqli_fetch_assoc, which takes your query and returns an associative array with the field names as keys. I kept it all procedural for the sake of uniformity (I hate mixing OOP with procedural). I should note that your code is horribly convoluted as written (for instance $key isn't defined anywhere). It's better to avoid reusing variable named like you have. I also HIGHLY recommend switching to an all-object codebase.
$result = mysqli_query($con, "SELECT referer FROM users WHERE userId = '$key'");
if($row = mysqli_fetch_assoc($result)){
$result2 = mysqli_query($con, "SELECT referer FROM users WHERE userId = '" . $row['referer'] . "'");
if($row2 = mysqli_fetch_assoc($result2)){
$result3 = mysqli_query($con, "SELECT refered FROM users WHERE userId = '" . $row2['referer'] . "'");
$newRefs = mysqli_fetch_assoc($result3);
mysqli_query($con, "UPDATE users SET refered = '" . $newRefs['refered'] . "' WHERE userId = '" . $row['referer'] . "'");
$result4 = mysqli_query($con, "SELECT userName FROM users WHERE userId = '$key'");
$refered = mysqli_fetch_assoc($result4);
}
}
You cannot use mysql_result!
Try to do it like this:
$result = mysqli_query($con, "SELECT referer FROM users WHERE userId = '$key'");
if( mysqli_num_rows($result, 0) ) {
list($referer) = mysqli_fetch_row($result);
....
You can use object oriented style:
$Result = $Con->query("SELECT referer FROM users WHERE userId = '$key'");
if( $Result->num_rows ) {
list($referer) = $Result->fetch_row();
If you're in the process of switching, you should go straight to PDO, not mysqli.
mysqli vs pdo - stackoverflow

SELECT Count php/sql

I am trying to store a mysql value into a php variable. I have the following query which I know works. However, I the value for $count is always 0. Can someone explain what I need to do to get the count value? The count should be the count of x's w here name_x=.$id.
$query = "SELECT COUNT(name_x) FROM Status where name_x=.$id.";
$result = mysql_query($query);
$count = $result;
Is first letter in table name is really capital. Please check it first.
or Try :
$query = "SELECT COUNT(*) as totalno FROM Status where name_x=".$id;
$result = mysql_query($query);
while($data=mysql_fetch_array($result)){
$count = $data['totalno'];
}
echo $count;
$query = "SELECT COUNT(*) FROM `Status` where `name_x`= $id";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$count = $row[0];
please try it
$query = "SELECT COUNT(*) FROM Status where name_x=$id";
$result = mysql_query($query);
$count = mysql_result($result, 0);
You are missing single quotes around $id. Should be
name_x = '" . $id . "'";

Categories