1

I'm having pretty simple bug but I just can't figure out why it happens.I have this array:

Array
(
    [1] => Array
        (
            [A] => Joakim
            [B] => Dzafic
            [C] => [email protected]
        )

    [2] => Array
        (
            [A] => Jevren
            [B] => Jevrej
            [C] => [email protected]
        )

)

And I'm trying to insert it into my MySQL database table like so:

 foreach($sheetData as $rec){
    $result=$mysqli->query("INSERT INTO `test`(`name`,`surname`,`email`) VALUES
                (
                ".$rec['A'].",
                ".$rec['B'].",
                ".$rec['C']."
                );");
                if(!$result){
                    var_dump($result);
                    die("Something's wrong with query!");
                }else{
                    echo 'Inserted!';
                }

            }

But it says: Something's wrong with query! and when I do var_dump($result); it says: bool(false) Please help me to debug this part of code because I'm pretty stuck with it.

2
  • change foreach($sheetData as $rec){ to foreach($sheetData as $key => $rec) { Commented Feb 23, 2016 at 9:14
  • You should use prepared statements.. Commented Feb 23, 2016 at 9:17

3 Answers 3

1

you forgot to add single quote ' values variable should be enclosed by ' if it contains string:

$result=$mysqli->query("INSERT INTO `test`(`name`,`surname`,`email`) VALUES
                (
                '".$rec['A']."',
                '".$rec['B']."',
                '".$rec['C']."'
                )");
Sign up to request clarification or add additional context in comments.

Comments

0

You should use $mysqli->error to check query error.

Write your code as below:-

foreach($sheetData as $rec){
    $result=$mysqli->query("INSERT INTO `test`(`name`,`surname`,`email`) VALUES
                (
                '{$rec['A']}',
                '{$rec['B']}',
                '{$rec['C']}',
                )");  // typo error here
                if(!$result){
                    printf("Errormessage: %s\n", $mysqli->error); // check error
                    var_dump($result);
                    die("Something's wrong with query!");
                }else{
                    echo 'Inserted!';
                }

}

Hope it will help you :)

Comments

0

A little hint for the future, when you have such problems: var_dump($my_query)

Then you see where the syntax error is or what is going wrong there anyway. :-)

Don't forget to escape the value strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.