-1

the following code that want to get data from mysql database using foreach($result as $post),and output in html ,but it's return null,thx a lot,need your help?

<?php
 $db = mysqli_connect('localhost','xxx','xxx','database')
 or die('Error connecting to MySQL server.');
 mysqli_query($db,"SET NAMES utf8");
?>

<html>
<head>
</head>
<body>
<h1>Demo </h1>

<?php

$query = "SELECT typename,typeurl FROM `posts_table`";
$result = mysqli_query($db, $query);

// output template: 
foreach($result as $post)
{
?>
    <div class="post">
        <p><?=$post['typename']?></p>
        <div class="info">
            posted at <?=$post['typeurl']?>, 
            <a href="./comment-url?id=<?=$post['typeurl']?>"><?=$post['typename']?> comment(s)</a>
        </div>
    </div>
<?
}

?>

</body>
</html>
slackware
  • 1
  • 1

2 Answers2

1

You are attempting a query with $query1 when it should be $query

$query = "SELECT typename,typeurl FROM `posts_table`";
$result = mysqli_query($db, $query);
Ben
  • 345
  • 2
  • 10
  • will `$result` variable contain data according to your code? – urfusion Nov 19 '16 at 15:19
  • If the query was successful, yes, then you can loop over it like that. According to your answer, @urfusion you only fetch one row – Qirel Nov 19 '16 at 15:21
0

There are few mistake in your question. Such as you assigned your query in variable $query but pass $query1 in mysqli_query function.

and for fetching results you need to first use mysqli_fetch_array

$result = mysqli_query($db, $query);
$result = mysqli_fetch_array($result,MYSQLI_ASSOC);
foreach($result as $post)
{
  // rest of code
}
urfusion
  • 5,528
  • 5
  • 50
  • 87