How do I update a query correctly - php

Whats wrong with my code?
Basically what I'm trying to do is add a number and update a field in the sql with what is connected to the variable. But since steamids look like this STEAM_0:0:123123123 or STEAM_0:1:123123123 I get this
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 ':0:14166834' at line 1
This is just for learning, so I know my code has useless echos, but its just to see it being added and making sure i was doing it correctly anyways
addmoney.php
<?php
include("inc/config.php");
$mysteamid=mysql_real_escape_string($_POST['mysteamid']);
$sql = "SELECT * FROM $tbl_name WHERE steamid='$mysteamid'";
$result=mysql_query($sql);
$cash=mysql_result($result, 0, 'cash'); // outputs 7th
echo $cash;
$newcash= $cash + "10000";
echo "\n";
echo $newcash;
mysql_query("UPDATE $tbl_name SET `cash` = $newcash WHERE `steamid` = $mysteamid") or die(mysql_error());
?>
index.php contains a working formdata its not really required with the error in my code.
my main problem is this line from addmoney.php which is
$mysql_query("UPDATE $tbl_name SET `cash` = $newcash WHERE `steamid` = $mysteamid") or die(mysql_error());

As your steamid field in your DB is a string (it seems to be, as possible values are STEAM_0:0:123123123 and STEAM_0:1:123123123), you must use quotes arround the value :
mysql_query("UPDATE $tbl_name SET `cash` = $newcash WHERE `steamid` = '$mysteamid'");
Using mysql_real_escape_string() is necessary, as it escapes quotes inside the variable you pass it as a parameter -- but you still have to put quotes arround the string, in your SQL queries.

In the first query you surrounded your $mysteamid value with simple quotes, and in the second query you didn't. If the steamid is a string type, you need to surround the value with quotes, like
"UPDATE $tbl_name SET `cash` = $newcash WHERE `steamid` =' $mysteamid'"

Related

SQL syntax which sending me an Error

I have a Mysql Database named user. Here is a picture:
I want to change the Username of the user "dodlo.rg" programmatically.
Actually, I have the PHP-Version 7.1. And this is a part of my PHPCode:
EDITED CODE:
$newName= $_POST["changeT"];
$userId = $_POST["userId"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '$newName' WHERE user_id = '$userId'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
But I get the Error: "You gave an Error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM user' at line 1"
Thanks in advance.
The problem lies in 2 parts.
Firstly, since this column is a varchar field it needs to be inside quotes else it produces an sql error.
Secondly the SELECT statement just after is not valid, but i guess it was a copy/paste error.
Therefore your working code should be:
$newName= $_POST["changeT"];
$db = mysqli_connect("trolö", "trolö", "trolö123", "trolö")
$sql = "UPDATE user SET username = '".addslashes($newName)."' WHERE username = 'dodlo.rg'";
$query = mysqli_query($db, $sql);
$response["successU"] = true;
Also, please consider using your primary keys on your where statement rather a varchar field, as it'll improve speed when more complex queries. (eg. where user_id = 35 instead of where username = 'dodlo.rg' ).
Lastly, but quite important this code might be vulnerable to sql injections. You need to use prepared statements.
You have to convert this query into two parts
$sql1 = "UPDATE user SET username = $newName WHERE username = 'dodlo.rg'";
$sql2 = "SELECT * FROM user";

php mysql_query use variable as field name

I know that i shouldn't use mysql_query for make database query, but i need to modify an existing code.
What i need to do is to pass a php variable as field name of sql query.
I've try in this way:
$my_field = "field_name";
mysql_query("UPDATE my_table SET ".$my_field." =somevalue") or die(mysql_error());
but i've noticed that it's wrong, because resulting query is
UPDATE my_table SET =somevalue
What's the correct way to do it?
you missed the closing quotes, change to:
mysql_query("UPDATE my_table SET ".$my_field." =somevalue") or die(mysql_error());
for checking, add the statement to variable and echo it, as:
$my_field = "field_name";
$query = "UPDATE my_table SET ".$my_field." =somevalue");
echo $query; //see the output to check if it shows correct statement
try this
$my_field = "my_field";
$my_value = "my_value;
$query = "UPDATE my_table SET $my_field=$my_value");
php allows variables to work inside double quotes

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

Insert query problem with php mysql

This is simple one i am using the following insert query
mysql_query(insert into table1 set saltval = 'Y'Z' where uid ='1');
but i does not work becaues the value for the field saltval is Y'Z . my question is how to considered this value is as a string .
You need to escape any single quotes with a backslash.
mysql_query("insert into table1 set saltval = 'Y\'Z' where uid ='1'");
However your SQL is invalid as well... Did you mean to do an update? Insert statements don't have a where.
As mentioned in other answers, if the input is from a user then you should use mysql_real_escape_string()
http://www.php.net/manual/en/function.mysql-real-escape-string.php
$string = mysql_real_escape_string("Y'Z");
mysql_query("insert into table1 set saltval = '{$string}' where uid ='1'");
Always use mysql_real_escape_string() function for this if values come from user input
$query="insert into table1 set saltval = '".mysql_real_escape_string($InputVal)."' where uid ='1'";
See http://php.net/manual/en/function.mysql-real-escape-string.php
You have to add a backslash to certain characters to make your string fit into SQL syntax rules.
Assuming you're creating your query dynamically, PHP has special escaping function for this and you should use it for the every quoted string in the query, no exceptions.
So, write your code like this:
$salt = "Y'Z";
$id = 1;
$salt = mysql_real_escape_string($salt);
$id = mysql_real_escape_string($id);
$sql = "update table1 set saltval = '$salt' where uid ='$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
to make it safe and fault-tolerant

SQL error in php

Hey, I wrote some code for extracting some information out of the database and checking to see if it met the $_COOKIE data. But I am getting the error message:
Error: 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 ')' at line 1
My code so far is:
$con = mysql_connect("XXXX","XXXXX","XXXXXXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXXXXX", $con);
$id = $_COOKIE['id'];
$ends = $_COOKIE['ends'];
$userid = strtolower($_SESSION['username']);
$queryString = $_GET['information_from_http_address'];
$query = "SELECT * FROM XXXXX";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if ($queryString == $row["orderid"]){
$sql="UPDATE members SET orderid = ''WHERE (id = $id)";
$sql="UPDATE members SET level = 'X'WHERE (id = $id)";
$sql="UPDATE members SET payment = 'XXXX'WHERE (id = $id)";
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
}
}
Any help would be appreciated,
Thanks.
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
should be
$sql="UPDATE members SET ends = '$ends'WHERE (id = '$id')";
(IE add the ' around $id)
I'm not sure if this is the error, but do you realize you're code only runs the last UPDATE? You're assigning $sql 4 time, and only running it after the fourth assignement...
If $_COOKIE['id'] does not have a value, then $id in your SQL statements will be blank, leaving your SQL looking like this:
UPDATE members SET ends = 'something' WHERE (id = )
which, of course, is invalid SQL.
Only one of the SQL statements will execute, and that's the last one. You need to add some whitespace before the WHERE clause, like this:
$sql="UPDATE members SET ends = '$ends' WHERE (id = $id)";
Also be wary of SQL injection attacks in the event that your cookie is altered by the end user. One other thing of note is your orderid column. Is it a VARCHAR or some other unique identifier? If it's an integer, then setting it to empty string will not work. You might want to rethink your schema a bit here.
EDIT: Another thing you need to do is check to make sure the cookies actually have values. If not, your SQL strings will be messed up. Have you though about using parameterized queries through PDO so you don't have to worry about SQL injection at all?
first of all you keep overwriting $sql variable so only the
$sql="UPDATE members SET ends = '$ends'WHERE (id = $id)";
is being executed.
And I would say that $id variable is not what you think it is (maybe empty as query like the one above without id:
$sql="UPDATE members SET ends = '$ends'WHERE (id = )";
would throw such error back.
Try
$id = NULL;
before
$id = $_COOKIE['id'];
if the error is gone that means that $id is not what you think it is

Categories