-3

我编辑我的代码运行良好,但仍然存在一个问题......从我的数据库中选择并显示在我的建议输入中的数据(只有一行和最后一个 ID)!我怎样才能显示我的数据库中的所有数据行????

<?php
$q = strtolower($_GET["q"]);

if (!$q) return;

$host = "localhost";
$user = "root";
$password = "";
$database = "private_message_system";

//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);

$query = mysql_query("SELECT * FROM users");


while($row = mysql_fetch_array($query)){


    $items = array($row["user_name"] => $row["user_email"]);    

}

$result = array();

foreach ($items as $key=>$value) {
if (strpos(strtolower($key), $q) !== false) {

    array_push($result, array(
        "name" => $key,
        "to" => $value
    ));
}
}

echo json_encode($result);
?>
4

2 回答 2

0

据我所知,mysql没有像postgres这样的数组类型,所以你必须一个一个地获取它:

// here is where you get your to connection to the database
$conn = mysql_connect("your IP", "username", "password");
mysql_select_db("mydb", $conn);

// here you have to do the select to retrieve data from the table.
$query = "SELECT `name`, `to` from mytable";

// now you got all the records but you still need to iterate over this result
$result = mysql_query($query, $conn);
$array = array();

  // retrieve a record and append it to the array
 while($record = mysql_fetch_assoc($result)):
   $array[] = $record;

 endwhile;

// please close the door.... 
 mysql_close($conn);
  echo json_encode($array);
于 2012-09-04T13:19:36.897 回答
0

有关连接到 MySQL 和搜索的基本实现,请参见下文$q,我为您留下了一些评论,以使您更清楚发生了什么!

<?php

// Get the query term from the url
$q = strtolower($_GET["q"]);

// Do nothing if it's empty or not set
if (empty($q)) return;

// Result array which we are going to get from MySQL
$result= array();

// Make a SQL Connection
mysql_connect("localhost", "admin", "password") or die(mysql_error());

// Try to connect to your DATABASE (change the name) or throw an error
mysql_select_db("DATABASE") or die(mysql_error());

// Get data from the "email" table 
// Where the name field is LIKE the search term
$result = mysql_query("SELECT * FROM email WHERE name LIKE '%".mysqli_real_escape_string($q)."%'") 
or die(mysql_error());  //throw an error if something went wrong

//Read all the results ($row) in a loop and put them in the result array
while($row = mysql_fetch_array( $result )) {
    $result[] = array('name' => $row['name'], 'to' => $row['to']);
} 

// Output the array as JSON
echo json_encode($result);

?>

对于 PHP 经验丰富的人,我知道您可以从 MySQL 获取一个数组,但为了使其更清晰,将其保留为这样。


启用错误报告

ini_set('display_errors', 1);
error_reporting(E_ALL);
于 2012-09-04T13:16:03.917 回答