我正在尝试让我的PHP脚本以简洁的顺序打印我数据库中的所有行。目前我没有得到任何东西。我的表有4列,Name,Address,Long和Lat,以及2行数据。该表称为位置。我使用以下代码,但我没有开始工作:
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
$resultArray = array();
$tempArray = array();
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
答案 0 :(得分:2)
这是一个使用pdo而不是mysqli
的简单示例<select id="xxx" name="xxx">
<option value="">Choose a car</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
你可以使用像这样的for循环来回显数据并自己格式化
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$pdo = new PDO('mysql:host=' . $dbHOST . ';dbname=' . $dbNAME, $dbUSER, $dbPASS); // create connection
$stmt = $pdo->prepare("SELECT Name, Address, Long, Lat FROM Locations");
//you should never use *, just call each field name you are going to use
$stmt->execute(); // run the statement
$arr = $stmt->fetchAll(PDO::FETCH_ASSOC); // fetch the rows and put into associative array
print_r($arr); // print all array items, unformatted
如果名称正确,则会显示您的行ID和行CITY。只需将名称更改为您的字段名称即可。如果您需要进一步的帮助,请随时提出。
但是,如果您想坚持使用mysqli,请将以下代码添加为wirl。
for($i=0; $i<sizeof($arr); $i++) { // this will loop through each row in the database. i prefer this method over while loops as testing has shown this is much faster for large scale tables
echo 'Name: ' . $arr[$i]['Name'] . '<br />'; // $arr is the array name, $i is the number of the array item, or iterator, ['Name'] is the field name
echo 'Address: ' . $arr[$i]['Address'] . '<br>';
echo 'Long: ' . $arr[$i]['Long'] . '<br>';
echo 'Lat: ' . $arr[$i]['Lat'] . '<br>';
}
将fieldname更改为您要显示的字段
编辑:粘贴以下代码。它将回显行数。这将告诉您查询语句是否正确。
$dbHOST = 'localhost';
$dbNAME = 'nilssoderstrom_';
$dbUSER = 'nilssoderstrom_';
$dbPASS = 'Durandal82!';
$mysqli = mysqli_connect($dbHOST, $dbUSER, $dbPASS, $dbNAME);
$query = "SELECT Name, Address, Long, Lat FROM Locations";
$result = mysqli_query($mysqli, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
echo 'Name: ' . $row['Name'] . '<br />';
echo 'Address: ' . $row['Address'] . '<br>';
echo 'Long: ' . $row['Long'] . '<br>';
echo 'Lat: ' . $row['Lat'] . '<br>';
}
}
答案 1 :(得分:0)
以关联数组的形式获取查询结果,并使用每个结果打印所有结果
<?php
$con=mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM `Locations` ";
if ($result = mysqli_query($con, $sql))
{
while($rows = mysqli_fetch_assoc($result)) {
foreach($rows as $key => $val)
{
echo $val;
}
}
}
mysqli_close($con);
?>