简体   繁体   中英

PHP Prepared Statement— Printing results

I am trying to display information from an SQL query that should only have one result. 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. Any insight?

As Jay Blanchard stated in the comment section of your question...

You ought to use <br /> as that tells the browser to read it as a new line. 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.

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.

See more on pre wrapping:

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

<?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
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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