简体   繁体   中英

Inserting data to mySQL table

In my php program, I have to insert variables into one of my sql tables. Every time I go to test this out though, the values don't get posted to the table. Is there something wrong with these statements? or is the problem bigger than these 2 lines

$sqli = mySQLi_connect("localhost","root","root","myProject");

mysqli_query("insert into purchases (id, productID, quantity) values ($id, $productID, $quantity)");    

Try it by using

mysqli_query("insert into purchases (id, productID, quantity) values ('$id', '$productID', '$quantity')"); 

you are missing a single quotes in those variables

If you use mysqli_query in a procedural way, you need to use the connection as your first parameter like this

mysqli_query($sqli, "insert into purchases (id, productID, quantity) 
    values ($id, $productID, $quantity)");

Otherwise you can use it in an OOP manner like this:

$sqli->query("insert into purchases (id, productID, quantity) 
    values ($id, $productID, $quantity)");

If you turned on error reporting on your code, you should have figured out the problem as the following warning is produced:

PHP Warning:  mysqli_query() expects at least 2 parameters, 1 given in /home/jkiang/test.php on line 10

First, you are mixing your procedural and your object oriented mysqli. Second, you have no error checking. Without knowing what your variables contain I suggest you try something like this:

$sqli = new mysqli_connect("localhost","root","root","myProject");

if($sqli->connect_errno > 0){
    die("Connection couldn't be established");
}

$q = "insert into purchases (id, productID, quantity) values ($id, $productID, $quantity)";

if(!$result = $sqli->query($q)){
    die("There was an error with your query");
}

$sqli->close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM