Fun with strings in PHP (Part 1)
Problem:
Concatenate and fetch data from two fields of database and then break it again.
Solution:
Posted below.
The description is included in the code.
You have to make a mysql database. The database part is as under:
create database test;
use test;
create table user(id int(9) not null auto_increment, first_name varchar(20), last_name varchar(20), primary key(id));
insert into user(first_name, last_name) values ("mukesh","chapagain");
PHP code below:
I have not used any loop (for, while, foreach, etc.) here to make the code simple. :-)
<html>
<head>
<title>Fun with strings</title>
</head>
<body>
<?php
// in my configuration, i am running mysql in localhost, my database username is 'root' and i don't have any database password
// i have a table called 'user' in the database 'test'
// connecting to the database server
mysql_connect("localhost","root","");
// connecting to the database
mysql_select_db("test");
// selecting data from table named 'user' where id = 1
$result = mysql_query("select concat(first_name,',',last_name) as name from user where id = '1'");
// fetching the result and assigning it to certain variables
while ($row = mysql_fetch_assoc($result))
{
$name = $row['name'];
echo "$name <br/>"; // you will get the result as first_name,last_name
}
$newName = explode(",",$name); // this will make an array with each name as values
//print_r($newName);
// print the first name as
echo "First Name: " . $newName[0] . "<br/>";
// print the second name as
echo "Second Name: " . $newName[1] . "<br/>";
// you can find about how many elements/items are there with the commas
$count = count($newName);
echo "Count: $count <br/>";
// there is a function called 'implode' which will join array elements with a string
$newNameTwo = implode(" ",$newName); // this will print the names with spaces in between... before the names were separated with comma
echo "$newNameTwo <br/>";
?>
</body>
</html>
Happy PHPing!


Leave your response!