PHP: Update database table - php

I'm trying to get this to update the messages table in my database, and set the message_read cell to 1.
But I can't get it to work. It always says 0 where it supposed to change to 1.
I'm pretty sure the variables are right.
$q = "UPDATE messages SET message_read='1' WHERE id='$messageid' AND to_user='$usermsg'";
mysql_query($q);
I do not get any errors either.
"usermsg" = the session username
"messageid" = the id of the message

Try this:
$q = "UPDATE messages SET message_read='1' WHERE id=".mysql_real_escape_string($messageid)." AND to_user='".mysql_real_escape_string($usermsg)."';";
$result = mysql_query($q);
if(!$result)
{
die( mysql_error() );
}
else
{
echo 'Number of affected rows:'.mysql_affected_rows();
}
If there was something wrong with your query you will be able to see the error printed on screen. And if not you can see how many rows were affected by the query.
I've also added some SQL injection projection just in case.

I think this is the correct syntax:
$q = "UPDATE messages SET message_read = 1 WHERE id = ".$messageid." AND to_user='".$usermsg."'";
Don't use quotes when the field type is INT.

Related

How would I make a php if statement update my sql column

My Problem
I'm trying to give persons over 16 special options on the website I am creating, but I'm struggling to get the PHP to check the age and then change the column to 1 for Yes or 0 for No.
What I've Tried
if ($account['age']>=16) {
echo 'True';
$sql = 'UPDATE accounts SET o16 = 1 WHERE id = ?';
} else {
echo 'False';
$sql = 'UPDATE accounts SET o16 = 0 WHERE id = ?';
};?>
I'm using MariaDB SQL at this moment.
It returns the values true or false but it does not change the value of the column.
I would be grateful if someone could help. I don't know if I have to do something different or if there's another way I could do this.
But what are you doing about the SQL? You are just doing an update but you don't execute it. Try somethings like this.
<?php
// $user_id = you put users id here, if you want to do it over session or something.
if ($account['age']>=16) {
echo 'True';
$sql = 'UPDATE accounts SET o16 = 1 WHERE id = ?';
$sql->bind_param('i',//$user_id);
$sql->execute();
} else {
echo 'False';
$sql = 'UPDATE accounts SET o16 = 0 WHERE id = ?';
$sql->bind_param('i',//$user_id);
$sql->execute();
}
Hope this helps you in some way, i think this could be right, but correct me if im wrong :)
use print_r($this->db->last_query()); to see the query and check under SQL execution in database server. You can check where you went wrong.

notice trying to get property in php when sql returns 0 row

I am trying to check if the stockid/s exist in peri or nonperi tbl. If the stockid belongs to peri, then I want to update peri. If not, the nonperi table will be updated.
What I did was to check first in the nonperi table and if the result is 0, then search again on nonperi tbl. Here is my code
//update nonperi table
$qryup = "UPDATE nonperi
SET bal='$balafter',modifiedby='$userid', modifiedon='$currdate'
WHERE stockid= $item";
$mysql1 = $conn->query($qryup);
if ($mysql1-> num_rows == 0)
{
//else if not in nonperi, update peri tbl instead
$qryup2 = "UPDATE peri
SET bal='$balafter',modifiedby='$userid', modifiedon='$currdate'
WHERE stockid= $item";
$mysql2 = $conn->query($qryup2);
}
The code works, it updates the nonperi if the result from peri tbl is 0, however, the notice of property obj etc is still displayed.
Do you have any suggestion on how to make this work, or any workaround or if you have any better code to achieve this without the error? PLease help. THanks in advance :)
Have you tried going with a prepared statement instead? I know I never had any notice when using those instead of directly query:
$qryup = "UPDATE nonperi
SET bal=:bal,modifiedby=:userid, modifiedon=:currdate
WHERE stockid= :id";
$stmt = $conn->prepare($qryup);
$stmt->bindValue(":bal", $balafter);
$stmt->bindValue(":userid", $userid);
$stmt->bindValue(":currdate", $currdate);
$stmt->bindValue(":id", $item);
$stmt->execute();
if ($stmt->rowCount() == 0)
{
//similar treatment here
}

Check if an user is in a database

I have developed a game with Javascript and when the user finishes it, I must save his record in a database. Here you see the code:
$temp = $_POST['playername']; //username
$text = file_get_contents('names.txt'); //list with all usernames
//this text file contains the names of the players that sent a record.
$con=mysqli_connect("localhost","username","pass","my_mk7vrlist");
if (stripos(strtolower($text), strtolower($temp)) !== false) {
//if the username is in the list, don't create a new record but edit the correct one
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
} else {
//The username is not in the list, so this is a new user --> add him in the database
mysqli_query($con, "INSERT INTO `mk7game` (`playername`,`record`,`country`,`timen`) VALUES ('".$_POST['playername']."', '".$_POST['dadate']."', '".$_POST['country']."', '".$_POST['time_e']."')");
file_put_contents("names.txt",$text."\n".$temp);
//update the list with this new name
}
//Close connection
mysqli_close($con);
When I have a new user (the part inside my "else") the code works correctly because I have a new row in my database.
When the username already exists in the list, it means that this player has already sent his record and so I must update the table. By the way I cannot edit the record on the player that has alredy sent the record.
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game` SET `record` = '".$_POST['dadate']."' WHERE `mk7game`.`playername` = ".$temp." LIMIT 1 ");
It looks like this is wrong, and I can't get why. I am pretty new with PHP and MySQL.
Do you have any suggestion?
You're missing quotes around $temp in the UPDATE statement:
mysqli_query($con, "UPDATE `my_mk7vrlist`.`mk7game`
SET `record` = '".$_POST['dadate']."'
WHERE `mk7game`.`playername` = '".$temp."'
^ ^
LIMIT 1 ") or die(mysqli_error($con));
However, it would be better to make use of prepared statements with parameters, rather than inserting strings into the query.
Escape your user input!
$temp = mysqli_real_escape_string($con, $_POST['playername']);
Make sure to stick your mysqli_connect() above that
$select = mysqli_query($con, "SELECT `id` FROM `mk7game` WHERE `playername` = '".$temp."'");
if(mysqli_num_rows($select))
exit("A player with that name already exists");
Whack that in before the UPDATE query, and you should be good to go - obviously, you'll need to edit it to match your table setup

My PHP SQL query is throwing errors, even though it works in the SQL console

I'm trying to create a function for my forum that will increment my user's "Posts" attribute by 1. For whatever reason, the following PHP does not work.
function postCountIncrease($username) {
//get the connection variable
global $con;
//change to the users database (this function works correctly)
sqlconnect_users();
//get current post number (this is also working)
$getCurrentPosts = "SELECT Posts\n"
. "FROM users\n"
. "WHERE Username='".$username."'";
$query1 = mysqli_query($con, $getCurrentPosts) or die(mysqli_error($con));
$currentPosts = mysqli_fetch_array($query1);
//here is the problematic post. Assume that $username is a valid value, and that I've already done mysqli_real_escape_string() on it
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
$query2 = mysqli_query($con, $incrementPostsQuery) or die(mysqli_error($con));
//return the result
$result = mysqli_fetch_array($query2);
return $result;
}
I honestly don't see what I'm doing wrong, because the SQL works fine. If I use UPDATE users.users SET Posts=1 WHERE Username='Lampitosgames' in the console, it works with no errors. Help is much appriciated. Also, here is the error it is throwing at me:
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 '1 WHERE Username='Lampitosgames''
You can not concatenate that way "toto ".$var+1, you have to surround with brackets "toto ".($var+1)
In your case, this is declaration of var $incrementPostsQuery which fails
Look at your errors, your syntax is off
$getCurrentPosts = "SELECT Posts
FROM users
WHERE Username='$username'";
The error is in the building of your query.
$incrementPostsQuery = "UPDATE users.users SET Posts=". $currentPosts[0]+1 ." WHERE Username='". $username ."'";
I'll suggest you some tips to create query like this:
"update table set field = value"; // you can write the value directly
"update table set field = ". $value; // easy
"update table set field = ". ($a+$b); // ...
"update table set field = {$value}"; // you can add a variable with curly braces
"update table set field = {$va[3]}"; // more compless way
"update table set field = {$a->b}"; // an object field

How do I update MySQL row in PHP?

I have a MySQL database that I'm working with, but when I try to update a row in it, it doesn't work. Here's the update code I'm working with:
mysql_query("UPDATE offtopic SET next = '$insert' WHERE id = '$id'");
First of all, you should make it a bit more safe:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = '%s'",
mysql_real_escape_string($insert),
mysql_real_escape_string($id));
Now, is your id actually string, and not numeric? If its numeric, you should rather have:
mysql_query(sprintf("UPDATE offtopic SET next = '%s' WHERE id = %d",
mysql_real_escape_string($insert), $id);
your syntax is correct, so it might be an error with the variables or your field names.
Try this:
$sql = "UPDATE offtopic SET next = '$insert' WHERE id = '$id'";
if (!mysql_query($sql)) {
echo "MySQL Error: " . mysql_error() . "<br />" . $sql;
}
That might show you some useful information to help you debug.
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories