PHP for Looping MySql id

时间:2016-08-13 03:43:49

标签: php mysql loops

我正在使用以下代码首先获取所有' id'来自MySql表。

<?php
$servername = "localhost";
$username = "**";
$password = "**";
$dbname = "**";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$slug = $_GET["category"];

$sql = "SELECT * FROM table WHERE category = '1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

$dealid = $row["dealid"];

}} else {}
$conn->close();
?>

$dealid应该返回所有ID,但它只返回1。

现在,下面的代码是显示带有这些ID的数据: -

<?php 
$num_rec_per_page=52;
mysql_connect('localhost','**','**');
mysql_select_db('**');
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$start_from = ($page-1) * $num_rec_per_page;

$sql = "SELECT * FROM table2 WHERE id = $dealid ORDER BY id DESC LIMIT $start_from, $num_rec_per_page";

$rs_result = mysql_query ($sql);
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<?php include( $_SERVER['DOCUMENT_ROOT'] . '/includes/dealbox.php' ); ?>

<?php 
}; 
?>

但它只显示1个数据,因为返回id仅为1.我无法理解问题所在。如果有人帮我解决了这个问题,那么任何帮助都是可以理解的,并且会有所帮助。

1 个答案:

答案 0 :(得分:0)

亲爱的朋友,所有Id都被设置为一个数组并返回该数组,

例如:

while ($row = mysql_fetch_assoc($rs_result)) 
{
  $dealid[]= $row['id']; //array creation
}

return ($dealid);