-2

I get the above error when i run the code. Please tell me where i've gone wrong.

I'm trying to get the values and encode them with JSON and save them into the database. Then later on i'm gonna retrieve the data from the database, decode it, and send it to the client end. Following is my php code.

    <?php

    $name = $_POST['fname']; 
    $email = $_POST['email'];
    $comment =$_POST['comment'];
    $website = $_POST ['website'];
    $rate = $_POST['rate'];


    $conn = mysqli_connect("localhost","root","","webtech");
    if(!$conn){
        die("Connection Failed : ".mysqli_connect_error());
    } else{
        echo "Connection Succesful ";
    }

    $jsonDb = array
    (
        'name' => $name,
        'email'=> $email,
        'comment'=> $comment,
        'website'=> $website,
        'rate'=> $rate 
        );

    $jsonArray = array
    (
        'name' => $name,
        'email'=> $email,
        'comment'=> $comment,
        'website'=> $website,
        'rate'=> $rate
         );

$encodeDatabase = json_encode($jsonDb);


$encodeArray = json_encode($jsonArray);
mysql_query("INSERT INTO comments VALUES ("."'".$jsonDb['name']."'"."," ."'".$jsonDb['email']."'".","."'".$jsonDb['website']."'".","."'".$jsonDb['comment']."'".","."'".$jsonDb['rate']."'".")");

    echo $encodeDatabase;




?>
Akila Randil
  • 205
  • 1
  • 10

3 Answers3

1

You have used mysqli to connect the DB but you are using mysql_query() to execute the insert query.

Please use mysqli_query() instead of mysql_query() to execute the Insert Query.

0
mysql_query("INSERT INTO comments VALUES ('$jsonDb[name]','$jsonDb[email]','$jsonDb[website]','$jsonDb[comment]','$jsonDb[rate]')");

That is what it should look like.

Joshua Byer
  • 524
  • 4
  • 11
  • Using string array keys without quoting them generates unnecessary E_NOTICE's. Another option is to use curly braces for interpolation, so instead of `'$jsonDb[name]'`, it would be `'{$jsonDb['name']}'`. Also note it is an error to use a mysql_* function after a mysqli_ connection. Not to mention this code is vulnerable to sql injection. – John McMahon Apr 19 '15 at 17:50
0

As others have pointed out you need to use mysqli_query instead of mysql_query in this case.

A couple more suggestions:

  1. With large string concatenation as in your query string it can become hard to read and easy to make mistakes with all of the single and double quotation marks. Another option is to use curly braces for interpolation, although this is mostly a stylistic choice:
"INSERT INTO comments VALUES ('{$jsonDb['name']}', '{$jsonDb['email']}', 
    '{$jsonDb['website']}', '{$jsonDb['comment']}', '{$jsonDb['rate']}')"
  1. This code is vulnerable to sql injection. Instead of inserting variables into the database using string concatenation for the query it would be much safer to use prepared statements.
John McMahon
  • 1,605
  • 1
  • 16
  • 21