Search code examples
phpmysqlforeachinsert

insert into php database "No Database Selected" Error


I have a foreach code which gathers data of each employee id from other tables (e.g. evaluation, attendance).

now I want to push these newly gathered data into a new table called dss so here is my code

$servername = "localhost";
$dbname = "ems_db";

// Create connection
$conn = new mysqli($servername,  $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO dss (emp_name, average, date)
VALUES ($name, $average, $date)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

and this is the result that I get

Error: INSERT INTO dss (emp_name, average, date) VALUES (Francis Ajax, 65, 2016-03-17)
No database selected
Error: INSERT INTO dss (emp_name, average, date) VALUES (Horus Skye, 66, 2016-03-17)
No database selected
Error: INSERT INTO dss (emp_name, average, date) VALUES (Lotus Po, 68, 2016-03-17)
No database selected

can someone please tell me what I'm doing wrong and how to fix it? :(

found new error

 Error: INSERT INTO dss (emp_name, average, date) VALUES (Lotus Po, 68, 2016-03-17)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Po, 68, 2016-03-17)' at line 2

I think its because the varchar needs the " " or ' ' but since my values came from variables I don't really know how to fix it..


Solution

  • Looks like your connection syntax is incorrect

    Try this:

    $conn = mysqli_connect($servername, $username, $password, $db_name);
    // By default $username = 'root' and $password = ''
    

    Hope this helps.