开发者

How to get information from 2 tables at once in PHP and MySQL?

开发者 https://www.devze.com 2023-03-08 02:56 出处:网络
<?php include(\'includes/config.php\'); $topi = $_GET[\'id\']; //id of url mysql_select_db(\"ban\", $con);
<?php 

include('includes/config.php');
$topi = $_GET['id']; //id of url

mysql_select_db("ban", $con);

$query = "SELECT * FROM `basic` WHERE id = '$topi' LIMIT 0, 30"; 

$result = mysql_query($query) or die(mysql_error());

$row = mysql_fetch_array($result) or die(mysql_error())开发者_如何学Python;

$aa = $row['item'];
$cc = $row['moreinfo'];
$dd = $row['contactinfo'];
$ff = $row['id'];

In this script, I get information from the table basic, but I want to retrieve data from another table named users. How can I retrieve data from two tables at once?

users table consists of following columns:

  • email
  • username
  • ID


You need to JOIN the two tables on a common value, called a foreign key. Once you've posted the structure of the users table as requested in the comments, I can provide a more complete example.

EDIT: See example. This calls explicit column names instead of SELECT *.

$query = "SELECT 
    basic.id,
    basic.item,
    basic.moreinfo,
    basic.contactinfo,
    users.email,
    users.username
  FROM basic JOIN users ON basic.id = users.id
  WHERE id   = '$topi'
  LIMIT 0 , 30"; 


You would use a JOIN onto the other table.

$query = "SELECT *
FROM basic b
JOIN users u ON b.user_id = u.user_id
WHERE id = '$topi'
LIMIT 0, 30";

Something like that, but based on your fields.

Please Note: the ON clause specifies what you will be looking for a match on.

0

精彩评论

暂无评论...
验证码 换一张
取 消