Using php $_SESSION in sql statements - php

I'm trying to update a table in my database. This is the code I have so far:
$query =
"UPDATE user
SET name='$name', pword='$pword', email='$email', address='$address', city='$city', state='$state', zip='$zip'
WHERE uname ='" . $_SESSION['uname'] . "'";
My page renders correctly but the table is never updated with the new data. I assume it's because the code can't figure our the whole $_SESSION part of this argument. Any ideas?
I'm trying to add this code to populate the $_SESSION['uname'] part of this...
$uname = $_SESSION["sname"]["uname"];
I'm trying to figure out where the sname came from myself...

There are lots of problems with this. It's very vulnerable to SQL injection, to begin with.
But the reason it's not updating your table is that $query is just a string. You don't show a MySQL, MySQLi, or PDO connection anywhere, and you don't show that you're executing the statement on a connection.
Based on your comment above, the problem is that $_SESSION['uname'] is either an empty string or undefined. Your problem isn't in this query; it's in some other part of your code.

<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$query = "SELECT uname FROM mytable WHERE somecondition LIMIT 1" or die("Error " . mysqli_error($link));
$result = $link->query($query);
while($row = mysqli_fecth_assoc($result)) {
$user=$row["uname"] ;
}
$_SESSION['uname']=$user;
?>
Here is some basic php to get the user from DB into SESSION,adapt it to your db. Dont forget session_start.

Related

PHP script to update mySQL database

another day another question...
I need to write PHP script to update mySQL database.
For example: updating profile page when user want to change their first name, last name or etc.
Here is my php script so far, it doesn't work. Please help!
<?php
# $db = new MySQLi('localhost','root','','myDB');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$First_Name2 = $_POST['First_Name2'];
$query = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";
$result = $db->query($query);
if(! $result)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
$db->close();
}
?>
THank you.
Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.
e.g. consider submitting "Fred" as the first name:
$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";
now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:
$query = "UPDATE people SET First_name = '$First_Name2' ...";
You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.
In short, this code is pure cargo-cult programming.

MySQL Update with variables in PHP

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$ID_No=$_POST['ID_No'];
$CurrentBalance = $_POST['CurrentBalance'];
$AddedAmount = $_POST['AddedAmount'];
$NewBalance = $CurrentBalance + $AddedAmount;
$sql = ("UPDATE balance
SET Balance= '$NewBalance'
WHERE ID_No= '$ID_No' ");
$result=mysql_query($sql);
if($result){
echo"Transaction successful!";
} else {
echo "&nbsp Error";
}
Hi guys I'm trying to update my certain values in my database with the use of variables. It updates when I use brute force and not variables. I know my variables are working because I printed them before queuing the update.
Remove the paranthesis outside this UPDATE Statement
$sql = ("UPDATE balance
SET Balance= '$NewBalance'
WHERE ID_No= '$ID_No' ");
It should be
$sql = "UPDATE balance
SET Balance= '$NewBalance'
WHERE ID_No= '$ID_No' ";
Also, add this mysql_error() to read the exact error when your query fails.
$result=mysql_query($sql) or die(mysql_error());
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
You forgot to add (dot) symbol.
$result = mysql_query("UPDATE balance SET Balance='".$NewBalance."' WHERE ID_No='".$ID_No."';");
This approach is bad and you might want to read this post to prevent SQL injection.

PHP/MYSQL Update query not working

Can anyone tell my why this update query is not working?
if ($_GET['update']) {
include 'config.php';
//Connect to MYSQL Database server
$connect = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Could not connect to MYSQL Database.");
$result = mysql_select_db(DB_NAME, $connect) or die("Could not connect to MYSQL table.");
mysql_query("UPDATE contact SET read = 1 WHERE id = '$_GET[update]'")or die("Query failed.");
echo "Update works!";
} else {
echo "Update does not work...ughh.";
}
Thank you in advance.
Edit: I got the query to work. For anyone who was worrying about the security, I was using this script as a test to see if I wanted to use it. I just added the security now that the script works. Thank you all for the help and tips.
What is column read?
mysql_query("UPDATE contact SET read = 1 WHERE id = '$_GET[update]'")
Judging by the non-capitalization of read, I suspect you are using a reserved word in MySQL for that column.
See:
Reserved Words in MySQL
To Get around this, just put a single quote around read. I.E.
mysql_query("UPDATE contact SET 'read' = 1 WHERE id = '$_GET[update]'")
Or better per j.bruni:
mysql_query("UPDATE contact SET `read` = 1 WHERE id = '$_GET[update]'")
Try this for your query line:
mysql_query("UPDATE contact SET read = 1 WHERE id = '".$_GET[update]."'")or die("Query failed: " . mysql_error());
Notice the change of the die() statement for better error handling:
die("Query failed: " . mysql_error());
*Also, just an FYI, you should really escape user variables (e.g. GET variables) like so to prevent SQL injections:
mysql_query("UPDATE contact SET read = 1 WHERE id = '".mysql_real_escape_string($_GET[update])."'")or die("Query failed: " . mysql_error());
Please report back the result.
I believe you need to escape the string to have $_GET['update'] to add it's value to the string. But you really should be using prepared statements least you be attacked by malicious users.
Prepared Statements: http://php.net/manual/en/pdo.prepared-statements.php
READ is a reserved word. You need to put it within backticks or rename your field.
Take a look at this link:
http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can test so
mysql_query("UPDATE contact SET read = 1 WHERE id = '".(int)$_GET['update']."'")or die("Query failed.");
if isn't this the problem specific
mysql_query("UPDATE contact SET read = 1 WHERE id = '.$_GET[update].'")or die("Query failed.");
echo "Update works!
Please try to not use the mysql_query. It's old and it's not efficient. why don't try to learn about the PDO and prepare statements .. ?

sql UPDATE error?

I've followed all the mySQL tutorials correctly but it still won't update the values in my table, can someone please help me?, these are my values below:
$editid = $_GET['id'];
$newtitle = $_POST['title'];
$newsneak = $_POST['sneak'];
$newbody = $_POST['body'];
$connect = mysql_connect("localhost","username","password") or die("Couldn't Connect. ");
mysql_select_db("dr") or die ("Couldn't Find DB.");
$query = mysql_query("SELECT * FROM news WHERE id=$editid");
$numrows = mysql_num_rows($query);
if($numrows=!0)
{
$querytitle = mysql_query("UPDATE news SET title=$newtitle WHERE id=$editid");
$querysneak = mysql_query("UPDATE news SET summary=$newsneak WHERE id=$editid");
$querybody = mysql_query("UPDATE news SET body=$newbody WHERE id=$editid");
header("Location: ../index.php");
}
On your select (add myql_error to check error):
$result = mysql_query("SELECT * FROM news WHERE id='$editid'");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
On your update:
$querytitle = mysql_query("UPDATE news SET title='$newtitle' WHERE id='$editid'");
$querysneak = mysql_query("UPDATE news SET summary=$newsneak WHERE id='$editid'");
$querybody = mysql_query("UPDATE news SET body='$newbody' WHERE id='$editid'");
use single quote around input data also use mysql_real_escape_string(); avoid sql injection.
PHP mysql_real_escape_string
As per #Tchalvak suggestion to include mention of binding, these are more updated tools against SQL Injections plus better optimization, but keep in mind PDO and MySQLi are supported if you have PHP 5+:
PHP PDO
and
PHP MySQLi
Can I add as well once you finish debugging to please remove any mysql_error() output? This is awesome info for attackers since it reveals database details. Either log it or don't show errors...adds a little extra security.
You want to use the mysql_error function to see what error your query returns.
As integration pointed out by Jeremy Conley, pay attention to don't let the mysql_error function output get published in your production HTML.

SELECT and UPDATE not working -- MySQL

After I upload a photo to a server, I want to save it in the user's database in MySQL, but for some reason, it is not working. Below is the code for uploader.php:
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
$con = mysql_connect("host","db","pw");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE fldID='$sess_userid' UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'");
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result);
I'm sure there is something very wrong with my query, but I can't figure out what it is. The photo is definitely being saved into the folder. But I simply want to update its path in the user database for later use. Thank you!
as it was mentioned already, you cannot use these two queries at once.
but there is also weird syntax: you're trying to use PHP's concatenation operator inside of mysql query.
And you did not escape a string parameter - very bad!
So, looks like you need something like
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$PortraitPath = mysql_real_escape_string('profileportraits/' . $_FILES['file']['name']);
$query = "UPDATE Members SET PortraitPath = '$PortraitPath' WHERE fldID='$sess_userid'";
You can do two separate queries:
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]'
WHERE fldID='$sess_userid';
And:
SELECT * FROM Members WHERE fldID='$sess_userid'
It seems you tried to put two queries(SELECT and UPDATE) into one query which will result in invalid query error.
Just wondering why you need two queries since you already know the userid and all you want is to update. All you need is to update the file path
UPDATE Members SET PortraitPath = 'profileportraits/' . '$_FILES[file][name]' WHERE fldID='$sess_userid';

Categories