I'm facing a problem in inserting some data into mysqli i tried everything same problem i don't know what's wrong here is the code
$mysqli = new mysqli("localhost", "root", "root", "root");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
function data($url, $items){
$domain = parse_url($url, PHP_URL_HOST);
switch($domain){
case 'test':
foreach($items as $item){
$tmp = explode("/", $item['link']);
$arr = array(1,2,3,4,5,6,7,8,9,0);
$author = ucwords(str_replace($arr, '', str_replace('-', ' ', $tmp[4])));
$description = strip_tags($item['description']);
$source = "Quoteee";
$img = "";
$date = date();
$sql = "INSERT INTO quote (id, quote, author, source, img, date, activated) VALUES
(NULL, '".$quote."', '".$author."', '".$source."', '".$img."', '".$date."', 1)";
$insert_row = $mysqli->query($sql);
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
}
break;
}
}
Just reread all your code and figured out that you initialized your mysql connection outside your function. To fix the problem you should move initialization into your function:
function data($url, $items){
$mysqli = new mysqli("localhost", "root", "root", "root");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
} else {
$domain = parse_url($url, PHP_URL_HOST);
switch($domain){
...
or you can try call global var like:
function data($url, $items){
global $mysqli;
...
But I would prefer 1st variant.
And the part I started from will help you to avoid sql injection and makes code more clear and easy to read and understand:
$stmt = $mysqli->prepare("INSERT INTO quote (quote, author, source, img, date, activated) VALUES ( ?, ?, ?, ?, ?, 1)");
$stmt->bind_param('sssss', $quote, $author, $source, $img, date("Y-m-d H:i:s", $date));
$stmt->execute();
$insert_row = $stmt->affected_rows;
if($insert_row){
You're inserting a NULL id each time, which I suspect is the problem.
If the id is auto incremented then simply leave it out of the insert query.
The query may be failing because the field is set to NOT NULL in the database
$sql = "INSERT INTO quote (quote, author, source, img, date, activated) VALUES ('".$quote."', '".$author."', '".$source."', '".$img."', '".$date."', 1)";
The mysql database object should be within the scope of the function data.
use the variable as global or place it inside the function