2017-08-10 160 views
2

我是PHP新手。我正在开发一个项目并且学习PHP。但我面临着一个忙碌的问题,我不知道为什么会发生这种情况。我有一个数据库名称表gift_items我试图通过PHP代码获取该表的数据。但是当在php和我的浏览器中运行查询时,会显示一些数据,而不是数据库中的完整数据。PHP没有从MySQL数据库中获取正确的数据

这里是我的ServerConnection.php

<?php 

$Server = 'localhost'; 
$username = 'root'; 
$password = ''; 


$database = 'db_gifters'; 


$connection = mysqli_connect($Server,$username,$password); 

if($connection) 
{ 
    mysqli_select_db($connection,$database); 
} 
else 
{ 
    echo "Could not connect to server"; 
} 


?> 

以及在index.php的PHP代码我在哪里实际运行查询的一部分。

<?php 
    $Listquery = "select giftname, gifttype from gift_items order by 
    gifttype,giftname";              

    $gifttype_query = "select distinct gifttype from gift_items";              

    $ListqueryResult = mysqli_query($connection,$Listquery);              

    $gifttype_queryResult = mysqli_query($connection,$gifttype_query);              

    $Listresult = mysqli_fetch_array($ListqueryResult);              

    $gifttype_result = mysqli_fetch_array($gifttype_queryResult);              

    foreach ($gifttype_result as $value)              
    { 
     echo $value; 
    } 
?> 

输出结果如下:它给我相同的数据的输出,而不是两次两个不同的数据值。给出 enter image description here

我在这里也安装结果在同一查询数据库中的画面拍摄ADN它给了我正确的结果,但在PHP代码它给我相同的值的两倍输出。

enter image description here 有人可以解决这个问题,或告诉我什么是我的脚本代码中的实际问题?有没有任何逻辑错误?

+0

同样的,请你*不*滥用片段的工具。这是仅用于HTML/CSS/Javascript * *。 –

+0

好。但我只是用它来更好地低估。真正的问题是什么。 –

+0

输出$ connection-> error其中#Grumpy ?? –

回答

1

您需要将数据作为关联数组而不是索引数组获取。它将解决问题。

还有另一篇文章,虽然使用PDO解释这样做的原因:PHP why does my function return twice the result of the array with different keys?

在这种情况下,只是你想从阵列中的每个查询。

mysqli_fetch_array([结果变量这里],MYSQLI_ASSOC)

$Listresult = mysqli_fetch_array($ListqueryResult,MYSQLI_ASSOC);              

$gifttype_result = mysqli_fetch_array($gifttype_queryResult,MYSQLI_ASSOC);              

foreach($gifttype_result as $value)              
{ 
    echo $value['gifttype']; 
} 

更多信息可以在这里阅读:Assoc. Array Fetch 礼貌PHP.net

+0

当我运行此代码时,它给出了错误“警告:非法字符串偏移'gifttype'在” 在 echo $ value ['gifttype']; –

+0

它通常意味着你试图使用一个字符串作为数组。在foreach循环var_dump($ Listresult)和var_dump($ gifttype_result)之前使用 并在此处显示您的结果。 –

相关问题