0

I'm trying to insert several values into a database.

First I add these values to array (function/other code omitted):

$name = (isset($_POST['name']) ? ($_POST['name']) : "name");
$email = (isset($_POST['email']) ? ($_POST['email']) : "email"); 
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string(md5($_POST['password']));

Like so:

$formvars = array();
array_push($formvars, $name, $email, $username, $password); 

Then call function to insert:

    $sql = array(); 
        for ($i = 0; $i < count($formvars);$i++) {
            $sql[] = $formvars[$i];
        }

        print_r(implode(',', $sql));

        $qry = 'INSERT INTO chinesegame (name, email, username, password) VALUES '. implode(',' , $sql);

        if(!$mysqli->query($qry))
        {
            echo "Error inserting data to the table \nquery:$qry";
            return false;
        }        

    return true;

My DB structure is as such:

enter image description here

It's giving me an insert error:

Error inserting data to the table query:INSERT INTO chinesegame (name, email, username, password) Dan,dthusky@gmail.com,danman,827ccb0eea8a706c4c34a16891f84e7b

Can I not build an insert string like that?

user3871
  • 12,432
  • 33
  • 128
  • 268
  • Strings ought to be quoted in SQL context. Also have you considered bound parameters? – mario Jan 02 '14 at 01:12
  • @mario I have trouble using those, so I went with real_escape_string. And can you elaborate on the string quotes in the SQL context – user3871 Jan 02 '14 at 01:13
  • Yes, `mysqli` is pretty awkward to use correctly. Check out [`pdo_query()`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php/20767765#20767765). – mario Jan 02 '14 at 21:15

2 Answers2

1

You forgot your "VALUES" keyword. and parenthesis help too. You also need all of the values to be in quotes, here is the correct version:

$qry = 'INSERT INTO chinesegame (name, email, username, password) VALUES ("'. implode('","' , $sql). '")';

Also, mysqli->query takes a connection variable first which has the connection information to the database, it should look like this:

$connection = mysqli_connect("localhost","my_user","my_password","my_db");
if(!$mysqli->query($connection, $qry))

Also, for the record,

    $sql = array(); 
    for ($i = 0; $i < count($formvars);$i++) {
        $sql[] = $formvars[$i];
    }

could be replaced with

$sql = $formvars;

there is no reason to loop through the whole thing getting them one at a time.

Damien Black
  • 5,579
  • 18
  • 24
0

It looks like you're missing a few things in the insert statement:

$qry = 'INSERT INTO chinesegame (name, email, username, password) '. implode(',' , $sql);

Try changing the insert statement to something like:

$qry = 'INSERT INTO chinesegame (name, email, username, password) VALUES ('. implode(',' , $sql).')';
Mr. Meeseeks
  • 1,841
  • 2
  • 21
  • 37