php - 将带有名字和姓氏的 mysql 字段拆分为 2 php echo

标签 php html mysql database mysqli

我在 mysql 中有一个字段,我在一个示例中存储名字和姓氏

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

如何只显示 John 或只显示 Smith?

最佳答案

最好是更改表并添加 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];

关于php - 将带有名字和姓氏的 mysql 字段拆分为 2 php echo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50140337/

相关文章:

javascript - javascript中输入的电话号码只能是整数,如果插入除整数之外的任何内容,则会出错

javascript - 覆盖层可通过在外部单击关闭

Mysql:按用户和案例编号选择最近的条目

php - MYSQL 用户定义的@VARIABLE

javascript - 关联变量及其 ID 的最佳方式

php - Wordpress 将搜索添加到自定义帖子类型存档

html - 如何使用附近的动态宽度按钮将标题居中?

php - 将 2700 多个文件名与数据库表中的 29000 多行进行比较

php - Mamp:第 31 行中的 DB Charset 错误

php - 使用 jquery-chosen 和选定的值