发布系统PHP / MySQL有错误?,警告:非法字符串偏移'描述'

时间:2015-02-01 09:24:50

标签: php mysql

我已经制作了2个简单的文本输入,存储在我的数据库中,然后使用foreach循环检索,因为我想显示表格中的所有内容(所有问题)。使用当前的代码,我得到了多个错误,并希望得到一些帮助。

此外,我不确定是否刷新页面,是否仍会在浏览器中显示所有问题或仅在我单击提交按钮时?如果是这样,请告诉我如何制作它,即使我刷新页面,所有问题都将显示在浏览器中。谢谢

The Errors are Warning: Illegal string offset 'question' in C:\xampp\htdocs\homepage\home.php on line 42
2


Warning: Illegal string offset 'description' in C:\xampp\htdocs\homepage\home.php on line 43
2


Warning: Illegal string offset 'question' in C:\xampp\htdocs\homepage\home.php on line 42
h


Warning: Illegal string offset 'description' in C:\xampp\htdocs\homepage\home.php on line 43
h


Warning: Illegal string offset 'question' in C:\xampp\htdocs\homepage\home.php on line 42
h


Warning: Illegal string offset 'description' in C:\xampp\htdocs\homepage\home.php on line 43
h



<?php

require_once "connection.php";

if(isset($_POST['submit'])) {


	$question = $_POST['question'];
	$description = $_POST['description'];

	$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );

	if($conn->connect_error) {

		die("connection error: " . $conn->connect_error);
	} else {

		echo "Submit button connected to database!";
	}

	

	$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
	(NULL, '{$question}', '{$description}' ) ";

	if($conn->query($sql)) {

		echo "it worked";
	} else {

		echo "error: " . $conn->error;

		exit();
	}


	$query = "SELECT * FROM `ask` ";

	if( $result = $conn->query($query)) {
		    $fetch = mysqli_fetch_array($result, MYSQL_ASSOC);
        foreach($fetch as $ques) {
            echo "<p> {$ques['question']}</p>";
            echo "<p> {$ques['description']}</p>";
        }
	} else {
		echo "failed to fetch array";
	}






}


?>


<!DOCTYPE html>
<html>
<head></head>
<body>



<div id="submitQuestion">

	<form action="" method="post">
		<input type="text" name="question"/>
		<textarea name="description" rows="10" cols="20"></textarea>
		<input type="submit" name="submit" value="ASK"/>
	</form>

</div>









</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

$query = "SELECT * FROM `ask` ";
$result = $conn->query($query);

if ($result->num_rows > 0) {
// output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<p> {$row['question']}</p>";
        echo "<p> {$row['description']}</p>";
   }
} else {
    echo "0 results";
}
$conn->close();

在此链接中查看更多帮助: http://www.w3schools.com/php/php_mysql_select.asp