2012-09-04 52 views
-3

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

<?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); 
?> 
+0

所以你要这些来自数据库? –

+1

我在这里没有看到任何MySQL。看起来你正在将数组转换为JSON。 – woz

回答

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); 
+1

请投票解释一下吗? –

+0

这是自动完成代码从建议结果中的文件名为emails.php的上述代码中获取结果建议,您将看到用户的姓名和电子邮件(Peter Pan“=>”[email protected]和“Molly”=>“molly @ yahoo.com“...等)我需要删除名称和电子邮件的,并从我的数据库中选择 –

+1

这正是上述代码所做的......请阅读评论... –

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); 
+1

请投票解释一下吗? –

+1

看到我的评论,*叹* –

+0

谢谢你的回答,但不工作 –