How to update database using `id`? - php

i want to update my database using id, I have already a database which have their name
Now when i update my database using WHERE college='1' it works successfully but when i update my database using id it's not working please help, and my database id=1 for which i'm working for..
here is my source code:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","members");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM admin");
while($row = mysqli_fetch_array($result))
{
echo "(".$row['id'].") ".$row['first_name']." ".$row['last_name'];
}
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora'
WHERE id='$id'");
mysqli_close($con);
?>
EDITED
after putting $id it's showing an error undefined variable id.. what's that meaning?

$id is not set in your code, referencing it will generate a warning and run the following query:
UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=''
You need to set $id somewhere.
Also be aware of SQL injection depending on where this value is coming from, if it is from user input it needs to either be casted to an integer or escaped if it is a string.
If it is an integer you need not include quotes around it (WHERE id=1 as opposed to WHERE id='1').

First your ID should be set and second your ID is probably not a string (varchar, char or text) in the database. It would be and should be numeric. In that the case, don't wrap the id in ''. Only string data should be wrapped in ''.

id is a number, not a string. Change it to:
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=".$row['id']);
EDIT
Your id is only used inside your loop. Try changing it from while to if
$result = mysqli_query($con,"SELECT * FROM admin limit 0, 1");
if ($row = mysqli_fetch_array($result)) {
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=$row['id']");
}
Any other way, using while, will change all user names in the table.
If you have more that one row in this table you'll need another approach.

try something like this,Remove single quotes
// Assign ID here
$id= 1;
mysqli_query($con,"UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id='$id'");

Define $id and then something like this should work:
if ($stmt = mysqli_prepare($conn, "UPDATE admin SET first_name='Rajendra', last_name='Arora' WHERE id=?")) {
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
}
If $id comes from a $_GET or $_POST variable, be sure to never embed it in a query directly!

Related

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

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

$_get not working

i created update code for updating password in a table using id.This is the url from where i am getting id using $_GET but its not working.
http://www.example.com/en/resetPaSS.php?id=1&token=779d2aa48de104db46d66e29de576aac
The code:
if(isset($_POST['sub']))
{
$pass_hash = PassHash::hash($_POST['pass']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$_GET[id]'";
$resu = mysqli_query($link,$sql);
//echo $sql;
if(!$resu)
{
$error="Unable to change Password. Try Again!";
}
else
{
echo"changed";
}
}
I also echo $sql and it shows UPDATE user SET password='$2a$10$bed9ad8e6cb910e0f1f12uXJldZLQ79f5HVrIiIAIZeZ9088Rre9.' WHERE id=''
Also tried $_REQUEST but still not works.
EDIT:
I am using this url for reseting password to send to the user which is created using
http://www.example.com/en/resetPaSS.php?id=$id&token=$token
try this:
$sql = "UPDATE user SET password='$pass_hash' WHERE id='" . mysqli_real_escape_string($_GET['id']) . "'";
If you use a form, then the id is not in the action url. You can also post the id by using a hidden input field
You must use prepared statement to prevent sql injection:
$sql = "UPDATE user SET password='?' WHERE id=?";
$stmt = $link->prepare($sql);
/* bind parameters */
$stmt->bind_param("si", $pass_hash, $_GET['id']);
/* execute query */
$stmt->execute();
EDIT
By clicking the link you will be go to your page where a form is. You have to edit the the id to the form or action url to make your script working by doing the following steps
make a variabele named id like this:
$id = isset($_GET['id']) ? $_GET['id'] : $_POST['id'];
also add hidden field to the form:
<input type="hidden" name="id" value="<?php echo $id; ?>">
Change the query bind_param to:
$stmt->bind_param("si", $pass_hash, $id);
If you know, that id is number, do this:
$id = intval($_GET['id']);
$sql = "UPDATE user SET password='$pass_hash' WHERE id='$id';";

How do I update a query correctly

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'"

Categories