这是我的代码
<?php
$host="localhost";
$user="root";
$pass="admin";
$dbname="news";
$connection=mysqli_connect($host,$user,$pass,$dbname);
if(mysqli_connect_errno())
{
die("Database Connection Failed >> Error Name : " . mysqli_error() . " Error number : " . mysqli_connect_errno());
}
$html = file_get_contents('http://www.thenews.com.pk/NewsSubIndex.aspx?ID=5'); //get the html returned from the following url
$pokemon_doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
$pokemon_doc->loadHTML($html);
libxml_clear_errors();
$pokemon_xpath = new DOMXPath($pokemon_doc);
$pokemon_row = $pokemon_xpath->query('//table[@id="ctl00_ContentPlaceHolder1_DataListSubIndex"]/tr');
foreach($pokemon_row as $row){
$headline= $row->nodeValue;
echo $headline;
$mysqli_query="INSERT INTO `thenews_entertainment` (`news`) VALUES ('".$headline."')";
echo $mysqli_query;
$result=mysqli_query($connection,$mysqli_query);
echo $result;
mysqli_close($connection);
break;
}
?>
我无法在数据库中插入记录。但是我已经回显了查询并从浏览器复制了该查询并在 mysql 控制台上执行,它成功插入了记录。为什么它没有从我的代码中插入。
最佳答案
您的代码中有两个基本缺陷。
- 缺乏准备好的陈述使用
- 缺乏错误报告。
无论您对此事有何看法,您都必须无条件拥有这两件事。
不过,第一个问题mysqli太麻烦了。所以,我建议改用 PDO。在 PDO tag wiki您会找到两者的教程。
重写您的代码以遵循这两个强制性规则,您将插入数据或一条错误消息,告诉您出了什么问题。
关于PHP数据库插入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22994836/