将mysql字段与firstname和lastname拆分为2个php echo

时间:2018-05-02 17:26:16

标签: php html mysql database mysqli

我在mysql中有一个字段,我在一个例子中存储了firstname和lastname

John Smith

我想在某些情况下只显示名字john,在其他情况下只显示姓氏,但显然如果我运行跟随查询,我会得到像John Smith这样的完整字段文本

$username=mysqli_real_escape_string($datacenter,$_POST['username']);
$check=mysqli_query($datacenter, "
SELECT * 
FROM `users` 
WHERE `username` = '$username' 
LIMIT 1");
if(mysqli_num_rows($check)>0){
while($display= mysqli_fetch_assoc($check)) {

显示它我运行

<?php echo $display['fullname']?>


Echo : John Smith

如何仅显示约翰或仅显示史密斯?

1 个答案:

答案 0 :(得分:2)

最好是更改表格并添加first_namelast_name然后更新它:

UPDATE `users` SET `first_name` = SUBSTRING_INDEX(`fullname`, ' ', 1),
                   `last_name`  = SUBSTRING_INDEX(`fullname`, ' ', -1)

或选择它们:

SELECT SUBSTRING_INDEX(`fullname`, ' ', 1)  as `first_name`,
       SUBSTRING_INDEX(`fullname`, ' ', -1) as `last_name`
       WHERE `username` = '$username' LIMIT 1

在PHP中(或分配给变量):

echo explode(' ', $display['fullname'])[0];
echo explode(' ', $display['fullname'])[1];