2013-03-28 85 views
3


我有2个表日,student_info在我databace student_payment ...如何从MySQL数据库的2表中选择数据....?

student_info我有:

ID,student_id数据,student_mail,student_pass,student_name,...

student_payment有:

ID,student_id数据,student_payment_id,student_payment_date,...

所以我的问题是在这里,我想选择student_name其中student_id形式student_info但我有问题和MySQL给我一个错误:

$db->connect(); 

$sql = "SELECT * FROM `student_payment`"; 
$rows = $db->fetch_all_array($sql); 
$student_id = $rows['student_id']; 

$sql2 = "SELECT * FROM `student_info` WHERE student_id=$student_id"; 
$rows2 = $db->fetch_all_array($sql2); 

$db->close(); 

foreach($rows as $record){ 
     // i wanna to use student_name in first line 
    echo "\n<tr> 
      <td>$record[student_id]</td> 
      <td dir=\"ltr\">$record[student_payment]</td> 
      <td dir=\"ltr\">$record[student_payment_id]</td> 
      <td dir=\"ltr\">$record[student_payment_bank]</td> 
      <td dir=\"ltr\">$record[student_payment_type]</td> 
      <td dir=\"ltr\">$record[student_payment_date]</td> 
      <td dir=\"ltr\"></td> 
      </tr>\n"; 
} 

,但我不知道如何连接student_id数据和student_name和foreach使用,因为我有2行数据。

(我在PHP/MySQL的初学者)

+0

'$ student_id = $ rows ['student_id'];'会为您提供数据集中最后一条记录的ID。 – asprin

回答

1

而不是查询数据库的两倍,可以改为参加表以获得您想要的行。尝试在PhpMyAdmin中或直接在MySQL浏览器中执行下面的查询。

SELECT a.*, b.* 
FROM student_info a 
     INNER JOIN student_payment b 
      ON a.student_ID = b.student_ID 
-- WHERE ...if you have extra conditions... 
ORDER BY b.student_payment_date DESC 

为了进一步获得更多的知识有关加入,请访问以下链接:

1

试试这个

$sql2 = "SELECT * FROM `student_info` WHERE student_id IN ($student_id)"; 
+0

这与当前语句相同:'$ sql2 =“SELECT * FROM \'student_info \'WHERE student_id = $ student_id”;' –

+0

我didi,但我有2行数据,我不知道如何使用它一起合作... –

1

有可能有内修复它JOIN,您可以加入2个表和使用1个查询中的两个值。

http://www.w3schools.com/sql/sql_join_inner.asp

或者你可以使用面向对象的方式,不知道这是你所需要的。 从2个查询中创建2个对象,并将它们放在一个foreach中。

1

试试这个

$sql2 = " SELECT * FROM `student_info` WHERE student_id= '$student_id' "; 
0

使用Mahmoud Gamal代码

但总是选择需要的列只不是所有的,因为

在表中的列未来数可能会增加,这可能会降低性能的应用。另外它可能包含一些不被泄露的重要信息。

1
foreach($rows as $record){ 
    // i wanna to use student_name in first line 
echo "\n<tr> 
     <td>$record[student_id]</td> 
     <td dir=\"ltr\">".$record['student_payment']."</td> 
     <td dir=\"ltr\">".$record['student_payment_id']."</td> 
     <td dir=\"ltr\">".$record['student_payment_bank']."</td> 
     <td dir=\"ltr\">".$record['student_payment_type']."</td> 
     <td dir=\"ltr\">".$record['student_payment_date']."</td> 
     <td dir=\"ltr\"></td> 
     </tr>\n"; 
} 
0

您好似想要报告所有付款。学生姓名将与付款信息一起显示。结果可能会有不止一个学生付款。

这个结果是由学生名称排序,然后付款日期(最近第一)

SELECT s.student_name, sp.* 
    FROM student_payment sp 
    INNER JOIN student_info s ON s.student_ID=sp.student_ID 
    ORDER BY s.student_name ASC, sp.student_payment_date DESC 
0

尝试加入该表,并使用单独的查询,而不是两个 - $ SQL =“SELECT * FROM student_info ,student_payment WHERE student_info.student_id = student_payment.student_id“