467,913 Members | 1,796 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,913 developers. It's quick & easy.

Trying to updating a column through php and mysql

Bit
Hello, so I'm trying to update a column (carID) in a table called users
but I'm getting the following error:
"syntax error, unexpected double-quote mark, expecting "-" or identifier or variable or number"

Can you help me figure out what's the problem in the code?

Expand|Select|Wrap|Line Numbers
  1. if($_SERVER["REQUEST_METHOD"] == "POST"){
  2.   $ID=mysqli_real_escape_string($con, $_GET['ID']);
  3. if(isset($_POST["rentit"])){
  4.  $sql="UPDATE users SET carID = '$ID' WHERE username = $_SESSION["username"] ";
  5. }}
Thanks A Lot!
Jan 18 '21 #1
  • viewed: 2035
Share:
3 Replies
Niheel
Expert Mod 2GB
the $_SESSION["username"] variable needs quotes in the SQL statement

original
Expand|Select|Wrap|Line Numbers
  1. $sql="UPDATE users SET carID = '$ID' WHERE username = $_SESSION["username"] ";
fix
Expand|Select|Wrap|Line Numbers
  1. $sql="UPDATE users SET carID = '$ID' WHERE username = '".$_SESSION["username"]."' ";
Jan 19 '21 #2
Bit
The explanation you are providing is really great.
Jan 19 '21 #3
16bit
This code has two big problems-
First you should always be using prepared statements to prevent SQL injection. The second, is that it is easier to avoid using
a session variable directly in SQL- it is better to set regular var to Session Var:

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. session_start();
  3. if ( !isset ($_POST['carid'] )) {
  4. exit('please input a carid');
  5. }
  6. $username = $_SESSION['username'];
  7. $carid = $_POST['carid'];
  8.  
  9. $host='database host';
  10. $user ='database user';
  11. $pass = 'database pass';
  12. $dbname = 'database name';
  13.  
  14. $con = mysqli_connect($host, $user, $pass, $dbname);
  15. $stmt = $con->prepare('UPDATE users SET carid= ? WHERE username= ?');
  16. $stmt->bind_param('ss', $carid, $username);
  17. $stmt->execute(); 
  18. $stmt->close();
  19. $con->close();
  20. ?>
  21.  
This is unnecessary:
Expand|Select|Wrap|Line Numbers
  1. if($_SERVER["REQUEST_METHOD"] == "POST") {
  2.  
  3. }
  4.  
because form data will ALWAYS use post if we use this in html (And therefore we don't need to check for POST method) :

Expand|Select|Wrap|Line Numbers
  1. <form action="/foo.php"  method="post">
  2.  
3 Days Ago #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by MySQL | last post: by
reply views Thread by Mark88 | last post: by
5 posts views Thread by erikthenomad | last post: by
1 post views Thread by Brett Magill | last post: by
1 post views Thread by smatta | last post: by
reply views Thread by tedpottel | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.