我正在创建一个论坛,用户可以通过提供问题和选项来创建投票。然后我使用Ajax和PHP将它们发送到数据库,并创建一个名为PollTable0的表。随着新的增加,数量增加s.a. “PollTable1”,“PollTable2”等。我通过计算数据库中的表数来获得这些数字。我的代码如下所示:
<?php
if (isset($_POST['NewPoll'])) {
$PollArray = $_POST['NewPoll'];
}
$con = mysqli_connect("localhost", "root", "123", "polldatabase") or die("DIE");
$getnumber = "SELECT COUNT(*) FROM information_schema.TABLES
WHERE TABLE_SCHEMA='polldatabase'";
$number = mysqli_query($con, $getnumber);
$sql = "CREATE TABLE PollTable" . $number . " (" . $PollArray[0] . "VarChar(255))";
mysqli_query($con, $sql);
for ($i = 1; $i < count($PollArray); $i++) {
$target = "ALTER TABLE PollTable" . $number . " ADD " . $PollArray[i] . " VARCHAR(255)";
mysqli_query($con, $target);
}
echo "Thank you for submitting your poll";
mysqli_close($con);
?>
现在问题是$ number是一个我相信的sql结果对象。因此,当使用$ number添加字符串时,它会给出错误:
Object of class mysqli_result could not be converted to string
如果我是对的,有没有办法将结果对象转换为字符串。我已经尝试过strval()和其他一些方法,但是没有用。 如果我错了,你认为我得到这个错误的原因是什么?提前谢谢。
答案 0 :(得分:1)
你应该在行后添加:
$number = mysqli_query($con, $getnumber);
以下几行:
$number = mysqli_fetch_row($number);
$number = $number[0];
mysqli_query仅查询数据库,但如果要获取结果,则需要使用以下功能之一:mysli_fetch_row
,mysqli_fetch_array
,mysqli_fetch_assoc
答案 1 :(得分:1)
问题在这里
$number = mysqli_query($con, $getnumber);
Mysqli :: query将返回
失败时返回FALSE。成功的SELECT,SHOW,DESCRIBE或 EXPLAIN查询mysqli_query()将返回一个mysqli_result对象。对于 其他成功的查询mysqli_query()将返回TRUE。
你在下一行使用$number
因此发出错误。
您需要在使用之前获取结果
http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
某事
$getnumber = "SELECT COUNT(*) as total FROM information_schema.TABLES
WHERE TABLE_SCHEMA='polldatabase'";
$result = mysqli_query($con, $getnumber);
$data = mysqli_fetch_assoc($result);
$number = $data['total'];
答案 2 :(得分:0)
您需要更改
$getnumber = "SELECT COUNT(*) FROM information_schema.TABLES
WHERE TABLE_SCHEMA='polldatabase'";
$number = mysqli_query($con, $getnumber);
到
$getnumber = "SELECT COUNT(*) as number FROM information_schema.TABLES
WHERE TABLE_SCHEMA='polldatabase'";
$query = mysqli_query($con, $getnumber);
$result = mysqli_fetch_object($query);
$number = $result->number;