Trying to updating a column through php and mysql

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Firas Rihan
    New Member
    • Jan 2021
    • 1

    Trying to updating a column through php and mysql

    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?

    Code:
    if($_SERVER["REQUEST_METHOD"] == "POST"){
      $ID=mysqli_real_escape_string($con, $_GET['ID']);
    if(isset($_POST["rentit"])){
     $sql="UPDATE users SET carID = '$ID' WHERE username = $_SESSION["username"] ";
    }}
    Thanks A Lot!
    Last edited by Dormilich; Jan 19 '21, 09:19 AM.
  • Niheel
    Recognized Expert Moderator Top Contributor
    • Jul 2005
    • 2432

    #2
    the $_SESSION["username"] variable needs quotes in the SQL statement

    original
    Code:
    $sql="UPDATE users SET carID = '$ID' WHERE username = $_SESSION["username"] ";
    fix
    Code:
    $sql="UPDATE users SET carID = '$ID' WHERE username = '".$_SESSION["username"]."' ";
    niheel @ bytes

    Comment

    • garyponting071
      New Member
      • Jan 2021
      • 1

      #3
      The explanation you are providing is really great.

      Comment

      • bakertaylor28
        New Member
        • Feb 2021
        • 45

        #4
        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:

        Code:
        <?php
        session_start();
        if ( !isset ($_POST['carid'] )) {
        exit('please input a carid');
        }
        $username = $_SESSION['username'];
        $carid = $_POST['carid'];
        
        $host='database host';
        $user ='database user';
        $pass = 'database pass';
        $dbname = 'database name';
        
        $con = mysqli_connect($host, $user, $pass, $dbname);
        $stmt = $con->prepare('UPDATE users SET carid= ? WHERE username= ?');
        $stmt->bind_param('ss', $carid, $username);
        $stmt->execute(); 
        $stmt->close();
        $con->close();
        ?>
        This is unnecessary:
        Code:
        if($_SERVER["REQUEST_METHOD"] == "POST") {
        
        }
        because form data will ALWAYS use post if we use this in html (And therefore we don't need to check for POST method) :

        Code:
        <form action="/foo.php"  method="post">

        Comment

        Working...