我正在尝试通过php在带有外键的表中插入值。该表称为游戏(ID,标题,年份,类型,publisher_id)。另一个表不包含外键,如下所示:Publisher(id,公司,地址,奖品,已发布)...
这是代码:
<h4>Insert new Game</h4>
<form method="get">
<input type="text" name="new-game"
<button type="submit">Submit Game</button>
</form>
<?php
if (isset($_GET["new-game"])){
require("MGconfig.php");
$newgame= $_GET["new-game"];
$id= mysqli_query($connection, "select max(id) from games");
$maxid= mysqli_fetch_row($id)[0]+1;
$publisher_id=mysqli_query($connection, "select title, company from publisher, games where publisher.id=publisher_id");
$insert ="insert into games (title, id, publisher_id) values (".$newgame.",".$maxid.",".$publisher_id.")";
$result=mysqli_query($connection,$insert);
if (!$result) {
echo "Erro na query ..." .mysqli_error($connection);
}
}
?>
我收到此错误(指向$ insert行):可捕获的致命错误:mysqli_result类的对象无法在第127行的C:\ xampp \ htdocs \ PHP \ MG_Dinamico \ admin.php中转换为字符串
这是配置文件:
<?php
$user = 'root';
$pwd = '';
$server = 'localhost';
$bdschema = 'MG';
$connection = mysqli_connect($server,$user, $pwd, $bdschema);
if (mysqli_connect_error()) {
echo "Error to DB ..." .mysqli_error($connection);
exit;
};
mysqli_set_charset($connection, "utf8");
//print_r($connection);
?>
我不知道如何使查询工作...建议?提前致谢!
最佳答案
首先,如果查询是针对单行或多行数据的,则必须在查询执行eevn之后进行查询访存。
注意:另一个重要的事情是,由于仅从发布者中选择标题,公司,因此您无法从选择语句中获得id
,因此您必须在该选择语句中也包含id
。
$publisher_id=mysqli_query($connection, "select id title, company from publisher, games where publisher.id=publisher_id");
之后,您必须运行fetch循环,以便它获取值,然后可以从中选择发布者ID。
<?php
$publisher_id=mysqli_query($connection, "select id title, company from publisher, games where publisher.id=publisher_id");
$count = $publisher_id->num_rows;
if($count==0)
{
$pub_id='';
}
else
{
while($row =$publisher_id->fetch_assoc())
{
$pub_id = $row['id'];// This will store the publisher ID
}
}
?>
现在,您可以将数据插入外键表,以便它具有与相应限制匹配的某些值。
$insert ="insert into games (title, id, publisher_id) values ('".$newgame."','".$maxid."','".$pub_id."')";
假定外键关系表中的发布者ID为NULL。
建议发布冰镇的答案
注意:不建议将代码发布为答案,然后先要求更正。如果您是问题的所有者,则可以直接在此处重新编辑问题广告。当您在这里时,请遵循SO规章制度,其中有些人确实想帮助有需要的人。
错误:1
题:
注意:尝试在第125行的C:\ xampp \ htdocs \ PHP \ MG_Dinamico \ admin.php中获取非对象的属性。
您进行的以下选择查询将永远无法使用。
$publisher_id=mysqli_query($connection, "select id, title, company from publisher, games where publisher.id=publisher_id");
此错误来自admin.php,因为您没有从上述select语句获得任何值。
答案与解释:
由于您在Where条件中使用了
publisher.id=publisher_id
,因此完全不建议使用。您在查询中将不会得到任何publisher_id
,查询将返回FALSE
。请遵循此行下方的注释,并检查您的对帐单中的错误,然后继续进行操作。确保您在此处有正确的查询,然后整个代码将正常运行。
注意:首先将echo放入Select语句,然后通过退出退出来中断执行。然后复制回显的语句并将其放在数据库的SQL中,然后检查插入是否发生任何错误。如果没有错误发生,则删除回显并删除出口;
从上述查询中获得结果后,您将获得发布者ID,然后可以将数据插入另一个表中。
错误:2
根据给定的建议(外键表)更改“插入查询”,您会丢失表列值上的滴答声。
现在,您可以将数据插入外键表,以便它具有与相应限制匹配的某些值。
$insert ="insert into games (title, id, publisher_id) values ('".$newgame."','".$maxid."','".$pub_id."')";
假定外键关系表中的发布者ID为NULL。
因为有时它可能没有关系ID。
关于php - PHP插入查询问题(外键),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39776103/