<?php
$con=mysqli_connect("localhost","user","password","database");
$post_id = '5';
$query= mysqli_query($con,"select t.tag_name from tag_map tm join article p on p.post_id = tm.post_id join tag t on t.tag_id = tm.tag_id where p.post_id = '$post_id'");
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
print_r($que);
}
?>
Array
(
[0] => audit
)
Array
(
[0] => income tax
)
输出并不是我想要的。我只需要像审计,所得税这样的价值。任何人都可以帮助我吗?
审计
所得税
答案 0 :(得分:1)
对于初学者,您应该使用预准备语句来避免SQL注入。之后,您可以使用mysqli::bind_result
或mysqli_stmt::get_result
和mysqli_result::fetch_array
。我将在这里展示这两种方法。
重要的是要采用这些实践,你使用的是mysqli而不是mysql,所以利用这个库带来的增强功能是有意义的。
首先,准备一份声明:
// initiate database connection
$db = mysqli_connect(
"localhost",
"user",
"password",
"database"
);
// set up your statement with ? parameters
$statment = $db->prepare('
SELECT
t.tag_name
FROM
tag_map tm
JOIN
article p ON
p.post_id = tm.post_id
JOIN
tag t ON
t.tag_id = tm.tag_id
WHERE
p.post_id = ?
');
// bind values for each parameter
$statement->bind_param('i', $post_id);
// execute the statement
$statement->execute();
上面的代码将安全地准备查询并在数据库中激活它,您现在已经有了一些结果可以使用。如上所述,您可以使用两种不同的方法。首先是bind_result
,如下所示:
// list the columns you want to get from each row as variables
$statement->bind_result($tagName);
// then loop the results and output the columns you bound above
while($statement->fetch()){
echo $tagName.'<br>';
}
第二种方法是使用get_result
,然后循环这些结果并使用fetch_array
来获取一个关联数组,您可以从中获取您之后的列,如下所示:< / p>
$result = $statement->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row['tag_name'].'<br>';
}
...无论哪种情况,请在完成后使用free_result
。
$statement->free_result();
<强>文档强>
mysqli::prepare
- http://www.php.net/manual/en/mysqli.prepare.php mysqli_stmt::get_result
- http://www.php.net/manual/en/mysqli-stmt.get-result.php mysqli_stmt::bind_param
- http://www.php.net/manual/en/mysqli-stmt.bind-param.php mysqli_stmt::bind_execute
- http://www.php.net/manual/en/mysqli-stmt.execute.php mysqli_stmt::bind_result
- http://www.php.net/manual/en/mysqli-stmt.bind-result.php mysqli_stmt::fetch
- http://www.php.net/manual/en/mysqli-stmt.fetch.php mysqli_result::fetch_array
- http://www.php.net/manual/en/mysqli-result.fetch-array.php 答案 1 :(得分:0)
试试这个,
<?php
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
echo $que[0];
}
?>
答案 2 :(得分:0)
如果您只想将结果作为一个assoc数组而不希望使用bind_param等,则可以使用php函数array_column
并在结果上使用特定的列名:
$result = array_column($connection->query('SELECT xy FROM table')->fetch_all(MYSQLI_ASSOC), 'xy');
答案 3 :(得分:-1)
<?php
$con=mysqli_connect("localhost","user","password","database");
$post_id = '5';
$query= mysqli_query($con,"select t.tag_name from tag_map tm join article p on p.post_id = tm.post_id join tag t on t.tag_id = tm.tag_id where p.post_id = '$post_id'");
while($que = mysqli_fetch_row($query))
{
echo $que[0];
}
?>
答案 4 :(得分:-1)
尝试使用$ que [0]:
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
print_r($que[0]);
}