user872148
user872148

Reputation: 102

How to insert data in to table from one variable?

How to insert this data in to table from one variable?

Table1 has fields: ID NAME ADDRESS

Data $strtoalvalue= 1 jam usa 2 dara usa 3 david usa

HOw to insert data from $strtoalvalue to Table1 by using PHP and mysql.

Upvotes: 1

Views: 129

Answers (1)

BumbleShrimp
BumbleShrimp

Reputation: 2200

You can do a lot with a single string if you format it and then convert it into an array.

These are two commands that are very useful for this:

explode()

implode()

You said your data is "1 jam usa 2 dara usa 3 david usa", so lets put this into a usable string format:

$strtoalvalue= "1,jam,usa|2,dara,usa|3,david,usa";

Next, you use explode() to turn this into an array:

$firstarray = explode("|",$strtovalue);

Now you have an array with these three strings in it:

$firstarray[0] = "1,jam,usa"
$firstarray[1] = "2,dara,usa"
$firstarray[2] = "3,david,usa"

next, you can loop through $firstarray, and convert each of it's strings into an array containing the values:

foreach($firstarray as $datastring){
    $secondarray[] = explode(',',$data_string);
}

now your $secondarray contains 3 arrays, which contain your data separated into individual pieces. all you have to do now is access it like so:

foreach($secondarray as $data_array){
    $data_id = $data_array[0];
    $data_name = $data_array[1];
    $data_address = $data_array[2];

    $sql = "INSERT INTO table_name (id, name, address) VALUES ($data_id, '$data_name', '$data_address')";
    // execute your SQL here
}

However, this is not secure, you will want to escape your data before concatenating it into the SQL string like that, otherwise your script is prone to SQL injection

Upvotes: 3

Related Questions