我想搜索数据库,如果表已包含数据,如果没有则插入它
我使用 MySQLi 准备好的语句来执行此操作,因为数据来自其他来源。 这是我的代码,它不起作用。我不明白为什么我需要执行 $stmt->store_result()
才能运行 num_rows().. 因为如果我不运行 store_result,我会收到错误:
致命错误:在非对象上调用成员函数bind_param()
foreach($this->contents as $key => $dealer) {
foreach($dealer as $deals) {
$stmt = $mysqli->prepare("SELECT id, name FROM company WHERE name = ? LIMIT 1");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0) {
$companyid = // I don't know how to get the id from the query
} else {
$stmt->prepare("INSERT INTO company (name) VALUES (?)");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
}
$stmt->close();
}
}
基本上我希望代码检查公司表中是否已存在公司,然后检查后,如果公司存在,那么我需要记录公司的ID公司,以便我可以在其他查询中使用它,但如果它不存在,那么我需要记录公司名称,然后获取 ID,以便我可以在其他查询中使用它。
I'm using MySQLi prepared statements to do this because the data is coming from other sources.
Here's my code it doens't work man. I don't understand why I need to do $stmt->store_result()
in order to run num_rows().. Because If I don't run store_result, I would get an error:
Fatal error: Call to a member function bind_param() on a non-object
foreach($this->contents as $key => $dealer) {
foreach($dealer as $deals) {
$stmt = $mysqli->prepare("SELECT id, name FROM company WHERE name = ? LIMIT 1");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows() > 0) {
$companyid = // I don't know how to get the id from the query
} else {
$stmt->prepare("INSERT INTO company (name) VALUES (?)");
$stmt->bind_param("s", $deals['company']);
$stmt->execute();
}
$stmt->close();
}
}
Basically I want the code to check if the company already exists in the company table, then after checking it, if the company exists then I need to record the id of the company so i can use it in my other queries, but if it doesn't exists then I need to record the company name then get the id so i can use it in my other queries.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获取您的
$companyId
,您需要执行$stmt->bind_result()
和$stmt->fetch()
。 有关 fetch() 的文档To get your
$companyId
you need to do$stmt->bind_result()
and$stmt->fetch()
. Docs on fetch()