0

Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?

<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
    echo 'Connected to MySQL server successfully.</br>';

else
    echo 'Unable to connect to server</br>';

$database = mysqli_select_db($myConn,$myDB);
if($database)
    echo 'Connected to database...</br>';

else
    echo 'Database not found!</br>';

$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));

?>

3 Answers 3

1

You have to add single quotes around the values:

$query= "INSERT INTO users VALUES ('$var1','$var2')

Or better use prepared statements. See this for an example.

Sign up to request clarification or add additional context in comments.

Comments

0

In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:

$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";

Comments

0

if users table have only two columns, or two plus an auto-incrementing id the query is:

INSERT INTO users VALUES ('$var1','$var2')

if there are more columns or a non primary id the query is:

INSERT INTO users (col1,col2) VALUES ('$var1','$var2')

You also miss a parameter in the connection instantiation:

$mysqli = new mysqli($host, $uname,$pswd, $myDB);

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.