Is it possible to update a table using WHERE email = $_SESSION['email'] - php

I want to update an already existing table it only has email and I want to add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname, $lname')" WHERE email= '$_SESSION['email'].';

Your UPDATE has a syntax error (problem with apostrophes.)
INSERT will not update but multiply rows. That is not what you want to have.
Here is my suggested query:
$sql="UPDATE table SET fname='$fname', lname='$lname' WHERE email='".$_SESSION["email"]."'" ;

Fix your quotes, like so:
$sql="INSERT INTO $tbl_name(email) VALUES ( '" . $email . "') WHERE email = '" . $_SESSION['email'] . "'";

Try like this: In case of simple Update Query
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$user_email';
Insertion is not a good idea here. It might duplicate your records.
If you want to be more specific than Go like this: Just providing your general syntax. No real time Syntax:
$user_email = $_SESSION['email'];
$fname = 'Thierry';
$lname = 'Henry';
$check_user = 'SELECT * FROM table WHERE email = "user_email"';
if($check_user)
{
YOUR UPDATE QUERY
}
else
{
YOUR INSERT QUERY
}

In case you are using mysql_ functions you should also escape the input:
$email = mysql_real_escape_string($_SESSION['email']);
Disclaimer for idiots: This does not imply I suggest to use mysql_* functions. Use mysqli or PDO instead.
You should also check against NULL and empty values in your query.
$sql = "REPLACE INTO " . $table . "
SET email='" . $email . "'
WHERE email='" . $email . "'
AND email IS NOT NULL
AND email != ''";
From http://dev.mysql.com/doc/refman/5.0/en/replace.html:
REPLACE works exactly like INSERT, except that if an old row in the
table has the same value as a new row for a PRIMARY KEY or a UNIQUE
index, the old row is deleted before the new row is inserted.
Please don't downvote if this doesn't exactly fit, just use INSERT or UPDATE with the same syntax then.

Related

Multiple rows update - update column NULL if blank field

I have a form that updates multiple row ids with 6 fields, I am trying to get the correct code to set the column to NULL if there is nothing changed.
Below is my code.
What I am trying to do is at the (shippedto_customer), the update works fine if I dont add in the if statement, but I want the if statement in case user does not change the date for the field shippedto_customer.
Sorry if I am not explaining correctly.
if(isset($_POST['Submit']))
{
$count=count($_POST["id"]);
for($i=0;$i<$count;$i++){
$sql1="UPDATE $tbl_name SET status='" . $_POST['status'][$i] . "',
ship_from_factory='" . $_POST['ship_from_factory'][$i] . "',
shippedto_customer=if(shippedto_customer='',NULL,'" .
$_POST['shippedto_customer'][$i] . "'), ship_comments='" .
$_POST['ship_comments'][$i] . "' WHERE id='" . $_POST['id'][$i] . "'";
$result1=mysql_query($sql1);
}
}
You're testing the old shippedto_customer in the table, not the value from the form.
You can use the NULLIF() function to test if the value being stored is an empty string, and store NULL instead.
if(isset($_POST['Submit']))
{
$count=count($_POST["id"]);
for($i=0;$i<$count;$i++){
$status = mysql_real_escape_string($_POST['status'][$i]);
$ship_from_factory = mysql_real_escape_string($_POST['ship_from_factory'][$i]);
$shipped_to_customer = mysql_real_escape_string($_POST['shippedto_customer'][$i]);
}
$ship_comments = mysql_real_escape_string($_POST['ship_comments'][$i]);
$id = mysql_real_escape_string($_POST['id'][$i]);
$sql1="UPDATE $tbl_name
SET status='$staus', ship_from_factory='$ship_from_factory',
shippedto_customer=NULLIF('$shipped_to_customer', ''),
ship_comments='$ship_comments' WHERE id='$id'";
$result1=mysql_query($sql1);
}
}
If you're forced to use the old mysql extension, you need to escape all the parameters. I've shown that above. But as mentioned in the comments, you should migrate to a modern MySQL API (I recomment PDO) and use prepared statements. If you do this, a PHP null value will be converted automatically to SQL NULL when used as a parameter.

Confused about PHP syntax for inserting variables in SQL query

$firstName = mysqli_real_escape_string($dbcon, $_POST['newFirstName']);
$lastName = mysqli_real_escape_string($dbcon, $_POST['newLastName']);
$emailAddress = mysqli_real_escape_string($dbcon, $_POST['newEmailAddress']);
$sqlQuery = "INSERT INTO admins (firstname, lastname, email) VALUES ('$firstName','$lastName','$emailAddress')
ON DUPLICATE KEY UPDATE firstname ='".$firstName."' lastname='".$lastName."' email='".$emailAddress."'";
My issue is on the last line. AFAIK you have to use double quotes for PHP to actually insert your variable into the string, but no matter what quotes I use I get errors. What's the proper syntax for inserting the variables?
You are missing commas from your SQL query in between the parameters you are updating.
Additionally for your update statement, you need to specify the table and SET:
"Update admins
Set firstname = '". $firstname . "' , lastname = '" . $lastname . "' " etc.
You should separate the columns you're updating with a comma. e.g:
ON DUPLICATE KEY UPDATE firstname ='".$firstName."', lastname='".$lastName."',
email='".$emailAddress."'";

Get ID of an inserted row in sql

I am creating a forum service ( https://www.orbitrondev.com/forum/ )
When someone creates a new thread it will execute:
// Example values
$UserID = 23123;
$ForumID = 1;
$ThreadName = 'Example title';
$sQuery = 'INSERT INTO threads (user_id, board_id, topic, time, lastPostUserId, lastPostTime)
VALUES ("' . $UserID . '", "' . $ForumID . '", "' . $ThreadName . '", "' . $time . '", "' . $UserID . '", "' . $time . '")';
The ID is in the column thread_id
Now I have to get the ID (thread_id) of the inserted row. So I can create a post, and to create a post I need the ID.
I thought about getting the last inserted thread id an adding 1 so I have the id, but SQL looks finer :P
How can I know the thread_id value for the newly inserted row?
You should use mysqli::$insert_id.
Where $mysqli is your connection;
$result = $mysqli->query($sQuery);
$lastid = $mysqli->insert_id;
Although you should use prepared statements when inserting data into the database.
Note: You need to have an auto incremented ID field in the database for this to work.
You have;
$oResult = $Database->query($sQuery);
$ThreadID = $oResult->insert_id;
which will not work.
You should use the connection to find the last inserted ID, like this;
$oResult = $Database->query($sQuery);
$ThreadID = $Database->insert_id;
Hope this helps.
You can retrieve the most recent AUTO_INCREMENT value with the
LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function.
These functions are connection-specific, so their return values are
not affected by another connection which is also performing inserts
http://dev.mysql.com/doc/refman/5.1/en/example-auto-increment.html
mysqli::$insert_id -- mysqli_insert_id — Returns the auto generated id
used in the last query
http://php.net/manual/en/mysqli.insert-id.php

{plain}password in Database and login error

I am coding a login panel to access to an Administration Panel.
The data (username and passw) are stored in a MySQL Database (type: InnoDB).
Looking in the tables the passwords are stored as plain and in the field password I have:
{plain}password.
Adapting a code that I already have, I have some problems because that {plain} thing is confusing me a bit.
My old code is:
// Construct SQL statement for query & execute
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '" . md5($password) . "'";
$result = $mysqli->query($sql) or die(mysql_error());
So if I replace the "{plain}password" from the field in the database with an MD5 password, the code works great, but if I modify my code to the following one:
// Construct SQL statement for query & execute
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '" . $password . "'";
$result = $mysqli->query($sql) or die(mysql_error());
I can't login because the password is wrong!
Any idea how to fix this?
If there is the prefix "{plain}" in front of the real password, you have to adjust your query to include that prefix.
$sql = "SELECT * FROM table WHERE user = '" . $username . "' AND password = '{plain}" . $password . "'";
$result = $mysqli->query($sql) or die($mysqli->error());
Also note that you should change mysql_error() in the die() command to use mysqli functions as well (so use $mysqli->error).
PS: You should have a look at how to store password nowadays. Storing them in plain text is not secure by any means.
EDIT
Mentioning the comment by #BrianRasmussen here as well:
Make sure $username and $password have been sanitzed before being used directly (using string concat) in a query! Otherwise your code is open to SQL injections of all sorts.
I don't know for sure what {plain} means, I guess it indicates that the password is in plain text - and this string is actually present. Hence, your second SQL should include it:
$sql = "SELECT * FROM table WHERE user = '" . mysql_real_escape_string($username) . "' AND password = '{plain}" . mysql_real_escape_string($password) . "'";
Note that I'm not starting the discussion about storing admin passwords in plain text, purely answering a technical question. However I must say that storing plain text passwords is a VERY bad idea.
Also note that I added mysql_real_escape_string to sanitise your input.

a very simple query is not working PHP

i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S
here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!
<?php
$email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];
$connection = mysql_connect('localhost','root','') ;
$db_selected = mysql_select_db("lab5" , $connection) ;
$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
while($row=mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($connection);
?>
You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.
You should also sanitize your inputs from SQL/XSS vulnerabilities.
The basic debugging steps are 1. adding
if (!$result) echo "Error: ".mysql_error();
to see any errors from the SQL query and 2. outputting
echo "Query: $query";
to see what the variables contain. One of these will point you to the problem.
Also, your query is vulnerable to SQL injection. You should add a
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
after fetching the values from the POST array.
Your error probably resides in the fact that you don’t escape your parameters.
While you are at it, use MySQLi or PDO (maybe even some prepared statements)
Someone mentioned your use of single-quotes, that’s the real error, my bad.
But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake
try
$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
or
$query = "select * From user where email='$email' and password='$password'" ;
Try this instead:
$query = "select * From user where email='" . $email . "' and password='" . $password . "';
Then immediately change that to this instead:
$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';
Try
$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";
You've confused the single and double quotes
You have:
$query = 'select * From user where email="$email" and password="$password" ' ;
You want:
$query = "select * From user where email='$email' and password='$password' " ;
Single quotes evaluate to whats literally inside. Double quotes will parse for variables inside. Theres also a curly brace {$variable} syntax you can use.
Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well. At the very least use mysql_real_escape on parameters that come from user input.
the problem is the way you are quoting the variables. Suppose that $email= 'some#gmail.com' and $password= 'securenot'.
what we want is the final interpreted string to be the following
select * from user where email='some#gmail.com' and password='securenot'
to achieve this we simply replace the some#gmail.com for $email and securenot for $password and get the following:
select * from user where email='$email' and password='$password'.
and then in php code ...
$query = "select * from user where email='$email' and password='$password'";
hope that is of some help
mysql_fetch_assoc() for associative array. You cannot use normal array as assoc array.
while($row=mysql_fetch_assoc($result))
{
echo $row['name'];
}

Categories