Currently I have an Array that looks like the following when output thru print_r();
Array ( [0] => Array ( [0] =>
Sri Chandrasekharendra Saraswathi Viswa Mahavidyalaya
| Kanchipuram, Chennai
[1] =>
Karpaga Vinayaga College of Engineering and Technology
| Kanchipuram, Chennai
[2] =>
SRM University, Chennai - Kattankulathur Campus
| Kattankulathur, Chennai
[3] =>
Saveetha University, Thandalam
| Thandalam, Chennai
[4] =>
B.S. Abdur Rahman Crescent University
| Vandalur, Chennai
[5] =>
P.B. College of Engineering
| Sriperumbudur, Chennai
[6] =>
Saveetha Engineering College
| Thandalam, Chennai
[7] =>
Hindustan University
| Kelambakkam, Chennai
I would like to insert this data into one table with each element value belonging to its respective field.
actually m scraping data from a website.i hv used some regex.all the array fetched contains 30 values each.all the arrays contains desired result but m nt able to figure out how to insert them into database.even your method is also nt working for me for loop used is:
for ($i=0;$i<30;$i++)
{ $temp1 = $names[1][$i];
$temp2 = $location[2][$i];
$temp3 = $facilities[1][$i];
$temp4 = $reviews[1][$i];
$sql = 'INSERT INTO collegedb (Name,Location,Facilities,Reviews) VALUES ("$temp1","$temp2","$temp3","$temp4")';
$run=mysqli_query($dbconnect,$sql);}
Can someone help me understand how I should approach this situation? here is a link to full code http://paste.ubuntu.com/24422534/
@Clearshot66 answer fits well with your question so this is extra: If you ever consider moving to PDO which is much better than mysqli may this helps you:
$req = $conn->prepare('INSERT INTO document (nom,date_creation,prix,auteur) VALUES (:nom, :date_creation, :prix
, :auteur)');
$req->execute(array('nom' => $document->getNom(), 'date_creation' => $document->getDateCreation()
, 'prix' => $document->getPrix(), 'auteur' => $document->getAuteur()));
Simple example of inserting an object of class Document in database secured. Good luck.
I don't know why people are telling you to use PDO when you're clearly using mysqli
The formatting of your data is a disaster, so I'll just make up some sample data we can work with
$data = [
'names' => ['first', 'second', 'third'],
'locations' => ['Berlin', 'Tokyo', 'Shanghai'],
'facilities' => [1, 4, 9],
'reviews' => ['good', 'best', 'average']
]
The goal will to be to insert data into our table like this
name location facility review
--------------------------------------
first Berlin 1 good
second Tokyo 4 best
third Shanghai 9 average
At the basis of our query, we will be using mysqli_prepare
which is intended to be used to (safely) inject variant data into a query
mysqli_bind_param
allows you to inject integers, doubles, strings, and binary blobs. In the examples below, we will be injecting strings s
and integers i
// basic example
$city = 'Reykjavik';
$stmt = $mysqli->prepare('select district from cities where city=?')
$stmt->bind_param('s', $city);
$stmt->execute();
In your case, we have an array of data tho, so we need to execute our query multiple times. Luckily, we can prepare a statement once, and bind/execute multiple times. A simple loop will do the trick
// make the statement
$stmt = $mysqli->prepare('insert into collegedb (Name, Location, Facilities, Reviews) VALUES (?, ?, ?, ?)');
// run it once for each set of values
for ($i=0; $i < count(data['names']); $i++) {
$name = $data['names'][$i];
$loc = $data['locations'][$i];
$fac = $data['facilities'][$i];
$rev = $data['reviews'][$i];
$stmt->bind_param('ssis', $name, $loc, $fac, $rev);
$stmt->execute();
}
// close the statement
$stmt->close();
Using array_map
makes this easier
If you have a recent version of PHP, you can make this solution a lot nicer using array_map
and a splat argument.
// make the statement
$stmt = $mysqli->prepare('insert into collegedb (Name, Location, Facilities, Reviews) VALUES (?, ?, ?, ?)');
// map over data
array_map(function($name, $loc, $fac, $rev) {
$stmt->bind_param('ssis', $name, $loc, $fac, $rev);
$stmt->execute();
}, ...array_values($data))
// close the statement
$stmt->close();
Even less hand-holding
The previous method using array_map
is fine, but disguised within the code is a 2d array transposition. Instead, we could write a generic transpose function, then first transpose your data, then loop over it. It will result in less cognitive load overall
$entries = [
['first', 'Berlin', 1, 'good'],
['second', 'Tokyo', 4, 'best'],
['third', 'Shanghai', 9, 'average']
];
We can derive $entries
from $data
using our handy array_transpose
function. Then looping over the data and executing our statement becomes a lot easier
// reusable transpose function
function array_transpose($xs) {
return array_map(null, ...array_values($xs));
}
// derive entry data
$entries = array_transpose($data);
// make the statement
$stmt = $mysqli->prepare('insert into collegedb (Name, Location, Facilities, Reviews) VALUES (?, ?, ?, ?)');
// run it once for each entry
foreach ($entries as $values) {
$stmt->bind_param('ssis', ...$values);
$stmt->execute();
}
// close the statement
$stmt->close();