Reputation: 29
I have a field in mysql where I store the firstname and lastname in one example
John Smith
I want to display only the firstname john in some cases and only the lastname in other cases but obviously if I run the follow query I get the complete field text like 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)) {
to display it I run
<?php echo $display['fullname']?>
Echo : John Smith
How to display only John or only Smith ?
Upvotes: 1
Views: 75
Reputation: 78994
Best would be to alter the table and add first_name
and last_name
and then update it:
UPDATE `users` SET `first_name` = SUBSTRING_INDEX(`fullname`, ' ', 1),
`last_name` = SUBSTRING_INDEX(`fullname`, ' ', -1)
Or to select them:
SELECT SUBSTRING_INDEX(`fullname`, ' ', 1) as `first_name`,
SUBSTRING_INDEX(`fullname`, ' ', -1) as `last_name`
WHERE `username` = '$username' LIMIT 1
In PHP (or assign to variables):
echo explode(' ', $display['fullname'])[0];
echo explode(' ', $display['fullname'])[1];
Upvotes: 2