[英]Extracting data from the database. how to write a loop function PHP MYSQL
The problem is the following.问题如下。 I have two tables users and cards.
我有两个表用户和卡。 How to write a loop function when a user has two or more cards?
当用户有两张或更多卡时,如何编写循环 function? Example: user bane has cards 222222 and 454545. however, when I send a question to the search field, it only throws out the first card.
示例:用户 bane 有卡片 222222 和 454545。但是,当我向搜索字段发送问题时,它只会抛出第一张卡片。
<?php
require "connection.php";
$search = $_POST['search'];
$sql = "SELECT users.first_name, users.second_name, cards.card_number
FROM users
INNER JOIN cards
ON cards.user_id = users.id
WHERE cards.card_number = '$search'
OR users.first_name = '$search'
OR users.second_name = '$search'";
$query = mysqli_query($db, $sql);
$result = mysqli_fetch_assoc($query);
echo $result['first_name']." ".$result['second_name']." ",
$result['card_number']; ?>
https://i.stack.imgur.com/0VvXF.jpg https://i.stack.imgur.com/0VvXF.jpg
Run跑
$results = mysqli_fetch_assoc($query);
foreach( $results as $result) {
echo .....
}
You are returning a single value.您正在返回一个值。 If I had to show all the user cards, I would do something like this.
如果我必须显示所有用户卡,我会做这样的事情。
<?php
require "connection.php";
$search = $_POST['search'];
$sql = "SELECT users.first_name, users.second_name, cards.card_number
FROM users
INNER JOIN cards
ON cards.user_id = users.id
WHERE
users.first_name = '$search'
OR users.second_name = '$search'";
$query = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($query)) {
echo $row['first_name']." ".$row['second_name']." ",
$row['card_number'];
}
?>
This should print a line for each card.这应该为每张卡片打印一行。
You could also change the where clause for something like this to find partial strings:您还可以更改类似这样的 where 子句以查找部分字符串:
users.first_name LIKE '%$search%'
But if you would like to be able to search for a card number and find all associated cards to its owner, then you must take some extra steps.但是,如果您希望能够搜索卡号并找到其所有者的所有关联卡,那么您必须采取一些额外的步骤。
I would go for something like this:我会为这样的事情 go :
SELECT t1.customerIDi, cards.number, customer.*
FROM CARDS
LEFT JOIN customer ON cards.CustomerID = customer.id
INNER JOIN (
SELECT customer.id AS customerIDi
FROM customer
LEFT JOIN cards
ON cards.CustomerID = customer.id
WHERE
Cards.Number = "$search"
) AS t1
ON t1.customerIDi = cards.CustomerID
http://sqlfiddle.com/#!9/82ad8/23/0 http://sqlfiddle.com/#!9/82ad8/23/0
I nested a select to find the card owner and then get all the associated cards.我嵌套了一个 select 来查找卡所有者,然后获取所有关联的卡。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.