Home » MySQL, PHP

Fun with strings in PHP (Part 1)

9 December 2007 40 views No Comment Popularity: 1% Share/Bookmark

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!

From Mukesh Chapagain's Blog | Post Fun with strings in PHP (Part 1)

Related posts:

  1. Session Handling in PHP
  2. How to get working site path and directory name in php?
  3. jQuery: Print array and object
  4. Very Useful SQL Queries with JOINS
  5. Very simple add, edit, delete, display in PHP

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.