简体   繁体   English

PHP准备的语句-打印结果

[英]PHP Prepared Statement— Printing results

I am trying to display information from an SQL query that should only have one result. 我试图显示来自SQL查询的信息,该信息应该只有一个结果。 I want to display the different columns in different places (with different formatting). 我想在不同的地方(使用不同的格式)显示不同的列。

Here is my current code: 这是我当前的代码:

$query = "SELECT artist_ID, name, description, years_active FROM artist WHERE name LIKE ?;";
if (!($stmt = $conn->prepare($query))) {
        echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
if (!$stmt->bind_param("s", $artist)) {
        echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
        echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->bind_result($artist_ID, $name, $description, $years_active);


while ($stmt->fetch()) {
        printf("%s", $name);
        printf("\n");
        printf("%s", $description);
}

Even though I've included the newline character, it just prints these two results on one line. 即使我包括了换行符,它也只是将这两个结果打印在一行上。 And I can't figure out how to print them without a while loop. 而且我不知道如何在没有while循环的情况下打印它们。 Any insight? 有见识吗?

As Jay Blanchard stated in the comment section of your question... 正如杰伊·布兰查德(Jay Blanchard)在问题的评论部分所说的那样...

You ought to use <br /> as that tells the browser to read it as a new line. 您应该使用<br />因为这会告诉浏览器将其读取为新行。 Because \\n and \\r simply writes a new line in the file output, and by default, the browser does not read a line break in a file as a new line unless there is a <br /> tag to tell the browser to read it as a new line. 因为\\n\\r只是在文件输出中写入新行,并且默认情况下,浏览器不会将文件中的换行符读取为新行,除非有<br />标记告诉浏览器读取作为新的一行。

Therefore: 因此:

printf("\n");

should be changed to: 应该更改为:

printf("<br />");

An alternative, if you want the browser to read the new line character as a new line, you can wrap the content in <pre></pre> tags. 或者,如果您希望浏览器将换行符读取为新行,则可以将内容包装在<pre></pre>标记中。

See more on pre wrapping: 查看更多有关预包装的信息:

http://www.w3schools.com/TAgs/tag_pre.asp http://www.w3schools.com/TAgs/tag_pre.asp

How do I wrap text in a pre tag? 如何在预标签中包装文字?

I hope you understand this code. 希望您理解此代码。 steps: Delete while loop Generate an associative array and save it into a variable ($row) Write a foreach loop so you can print the name and the description for each registry in your array 步骤:删除while循环生成一个关联数组并将其保存到变量($ row)中,编写一个foreach循环,以便您可以为数组中的每个注册表打印名称和说明。

<?php
if($row=$stmt->fetch_assoc()){
    foreach($row as $value){
?>

<!--HTML Code-->
<!--This is between the foreach and it's end (})-->
<!--So anything between here will be interpreted by your browser for each element in $row-->
<tr>
     <td><p><?php echo $row['name']?></p></td>
     <td><p><?php echo $row['description'] ?></p></td>
</tr>  

<?php
    } //end of foreach
}
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM