My SQL is not working - php

I'm trying to add a value to a row in a database table that currently has other values. I want to effect only one field in the table. here's what I'm doing:
$sql = "UPDATE users SET photo = ".$m_fname." WHERE pin = ".$_SESSION['pin'].";";
What's the correct way to do this?
Here's a little more:
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "UPDATE users SET photo = ".$m_fname." WHERE pin = ".$_SESSION['pin'].";";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}
Before anyone else downvotes..
I'm aware I should be using mysqli. Sorry if I offended anyone by using an old function.

Maybe this helps, it's a different implementation and it includes a proper way of data-sanitation:
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$updateQuery = $dbSession->prepare('
UPDATE
`users`
SET
`photo` = :photo
WHERE
`pin` = :pin');
$updateQuery->bindParam(':photo', $m_fname, PDO::PARAM_STR);
$updateQuery->bindParam(':pin', $_SESSION['pin'], PDO::PARAM_INT); // or 'PARAM_STR'
$updateQuery->execute();
See documentation for more functions available:
PHP Database Objects

Since you are setting the field photo to a string value, consider using single qutation
$sql = "
UPDATE `users`
SET `photo` = '" . $m_fname . "'
WHERE `pin` = " . $_SESSION['pin']; // Not clear what pin is (string or int)
What is the problem that you are facing? the code seems to be fine, provided that the PIN field is the primary unique key, and that photo is a varchar

use "'" for non number
$sql = "UPDATE users SET photo = '".$m_fname."' WHERE pin = '".$_SESSION['pin']."';";

$m_fname = mysql_real_escape_string($dest_filename);
$sql = "UPDATE users SET photo = '{$m_fname}' WHERE pin = '{$_SESSION['pin']}';";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}

Related

Unable to update a field in phpMyadmin using PHP

I have been trying to update a field in database using php, everytime I run the script there is no effect on the table. Here's how my code looks :
$sql="UPDATE users set sentMsg = $msg+1 where username = '$username' ";
$result = $link->query($sql);
where $link is the connection variable which is working fine with other queries.
Here's the table structure.
The $result variable is returning true.
I am unable to understand where the actual problem is.
Try this
$sql="UPDATE `users` SET `sentMsg` =".($msg+1)." WHERE `username` ='".$username."'";
$result = mysqli_query($link,$sql);
Thats what i could make out of your code till now.
try this;
$newCount = $msg+1;
$sql="UPDATE users set sentMsg = $newCount where username = '$username' ";
$result = $link->query($sql);
or
$sql="UPDATE users set sentMsg = ".($msg + 1)." where username = '$username' ";
$result = $link->query($sql);

Update two tables in one query

I can't update two table in one query. Is there any other way to do it? below is an example of my code.
$id = $_GET['idnum'];
$txtEditUsername=$_GET['txtEditUsername'];
$txtlname=$_GET['txtlname'];
$txtfname=$_GET['txtfname'];
$txtgender=$_GET['txtgender'];
$txtbdate=$_GET['txtbdate'];
$txtnationality=$_GET['txtnationality'];
$txtcnum=$_GET['txtcnum'];
$txtaddress=$_GET['txtaddress'];
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_query($conn, $sql)) {
} else {
echo "Error ".mysqli_error($conn);
}
You can use mysqli_multi_query like this
$sql = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
$sql .= "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname',
ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (mysqli_multi_query($conn, $query)) {
do {
/* sStockage du premier résultat */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* Affichage d'une séparation */
if (mysqli_more_results($conn)) {
printf("-----------------\n");
}
} while (mysqli_next_result($conn));
}
And here you can know more about it https://www.php.net/manual/en/mysqli.multi-query.php
You should use different name for variables like $sql and $sql2, but you can even use one query, try this:
UPDATE users, people
SET users.u_username = '$txtEditUsername',
people.ppl_lname = '$txtlname',
people.ppl_fname = '$txtfname',
// AND SO ON
WHERE
users.u_uid = '$id'
AND people.ppl_id = '$id';
EDIT
However, like someone else said, you can be victim of sql injection.
Try to use prepared statement with PDO, give a look here
The problem is here:
$sql = "UPDATE users ...";
$sql = "UPDATE people ...";
You are using the same variable to execute two different queries. The second statement overrides the first one, erasing it. That's why the users table isn't updated.
$usersSQL = "UPDATE users SET u_usernamee = '$txtEditUsername' WHERE u_uid = '$id'";
if (!mysqli_query($conn, $usersSQL)) {
echo "Error while updating users table: ".mysqli_error($conn);
// Eventually, consider to exit the function..
}
$peopleSQL = "UPDATE people SET ppl_lname = '$txtlname', ppl_fname = '$txtfname', ppl_gender = '$txtgender', ppl_bdate = '$txtbdate', ppl_nationality = '$txtnationality', ppl_cnum = '$txtcnum', ppl_address = '$txtaddress' WHERE ppl_id = '$id'";
if (!mysqli_query($conn, $peopleSQL)) {
echo "Error while updating people table: ".mysqli_error($conn);
}
Last but not least
Never ever use unsanitized data. Always filter and validate user's data.
Adding validation, you'll avoid passing invalid values to the query (example: ppl_lname's length is maximum 50 chars, and user sends 51 chars).
And most important, NEVER use user's data directly to a SQL query, because you are exposing your database to a serious risk.
Give a read to this link, or this one, they will explain what's the problem when using unsanitized data.

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

alert mysql column`s comment using php

I want to change my field comment using php but there is a problem!!
I need to get other column`s features :|
this is my code(gets all column features):
$query = "
SELECT
*
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = '$dbName' AND
TABLE_NAME = '$tableName' AND
COLUMN_NAME = '".$row->name."'";
$result = mysql_query($query) or die($query.'<br>'.mysql_error());
$tempRow = mysql_fetch_object($result);
this is my code that changes the comment
$query = "ALTER TABLE `$tableName`
MODIFY `".$row->name."`
".$tempRow->COLUMN_TYPE."
DEFAULT ".$tempRow->COLUMN_DEFAULT."
COMMENT '$comment'" ;
$result = mysql_query($query) or die($query.'<br>'.mysql_error());
but problem is that i lose some features , for example , outo increament , primary key ...
is there any way that i dont need to write all features , just change comment like update query ?!! if not how I should correct this query?!
Sorry about that, but there is no way to just change a single feature. You always have to specify all features that the column has. So extend your query to reflect all the column's features. All you need for that should be in $tempRow.
if ($tempRow->IS_NULLABLE == "NO")
{
$nullStr =" Not null ";
}else
{
$nullStr =" null ";
}
if (strlen($tempRow->COLUMN_DEFAULT) >0 )
{
$defaultStr = "DEFAULT ".$tempRow->COLUMN_DEFAULT;
}else
{
$defaultStr =" ";
}
if (strlen($tempRow->COLLATION_NAME )>0)
{
$collateStr = "collate " . $tempRow->COLLATION_NAME ;
}
$comment .= implode("|",$info);
$query = "ALTER TABLE `$tableName`
MODIFY `".$row->name."`
".$tempRow->COLUMN_TYPE."
".$nullStr."
".$extraStr."
".$defaultStr."
". $tempRow->EXTRA."
". $collateStr."
COMMENT '$comment'" ;

Check if a value is already in the table PHP/MYSQL

I'd like to check if a value is already in the table.
The structure of my table is this:
ApplicantId = INT
EventId = INT
StudentId = INT
No need to use unique because these table has dependencies.
Below is what I have tried so far:
include('../connectdb.php');
$ScholarPointId = $_GET["ScholarPointId"];
$Point = $_GET["Point"];
$ScholarId = $_GET["ScholarId"];
$EventId = $_GET["EventId"];
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId ='$ScholarId' ");
#$resultVerify = mysql_fetch_assoc($verifysql);
$num_rows = mysql_num_rows($verifysql);
if( $num_rows > 0 )
{
$script = "<script>
alert('The user has already attended this event!');
</script>";
header('updatescholarpoints.php');
exit();
}
else{
$result = mysql_query("UPDATE scholar_points
SET scholar_points.Points =
scholar_points.Points + $Point
WHERE scholar_points.ScholarPointId = '$ScholarPointId' ") or die(mysql_error());
mysql_query("INSERT INTO scholar_attended_events (EventId , ScholarId) VALUES( '$EventId' , '$ScholarId' ) ")
or die(mysql_error());
}
?>
What I want is to check if the EventId is already in taken by the Student = StudentId. If so, then system will prompt an alert box. Otherwise, Update and Insert into respective table. How can I do this? It seems I miss something in here. If you could help, I really appreciate it.
just missing an = ?
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId =$ScholarId ");
(and use PDO or mysqli, your code is really in a deprecated mode)

Categories