0

I am want to insert data into my phpmyadmin mysql database dynamically. So I get the values from user and then run the insert command of mysqli to insert the data.

But my insert command is not working. Here's my code:

$rest_name = $_SESSION['rest_name'];

    $order = $_SESSION['order'];
    $user = $_SESSION['username'];
    $bill = $_SESSION['bill'];
    $ctime = date("H:i:s", strtotime($_POST['time']));
        $insert_sql = "INSERT INTO '$rest_name' ('orders','amount',
'time','username')  VALUES('$order', '$bill', '$ctime','$user')';
    echo $insert_sql;
        if(mysqli_query($conn,$insert_sql)){
            echo "done";
        }
            else{
                echo "not done";
            }

I have 6 columns in the database but i need insert for 4 columns only the other two are set to default value.

halfer
  • 19,824
  • 17
  • 99
  • 186
Gopal Chandak
  • 387
  • 7
  • 19
  • 1
    The question highlighting tells you one of the problems (you didn't close with `"` - double). – FirstOne Mar 04 '16 at 19:01
  • Additional issues, SQL injection, quoting (in PHP), not checking errors. http://php.net/manual/en/mysqli.error.php http://php.net/manual/en/mysqli.quickstart.prepared-statements.php – chris85 Mar 04 '16 at 19:02

1 Answers1

0

There is a missing quotes at end of $insert_sql, try this instead:

$rest_name = $_SESSION['rest_name'];

$order = $_SESSION['order'];
$user = $_SESSION['username'];
$bill = $_SESSION['bill'];
$ctime = date("H:i:s", strtotime($_POST['time']));
    $insert_sql = "INSERT INTO '$rest_name' ('orders','amount','time','username')  VALUES('$order', '$bill', '$ctime','$user')'";
     echo $insert_sql;
    if(mysqli_query($conn,$insert_sql)){
        echo "done";
    }
        else{
            echo "not done";
        }

Also, with your method you can suffer with sql injection! try to avoid insert data this way! You should insert like this:

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}
Han Arantes
  • 775
  • 1
  • 7
  • 19