Reputation: 1
i have to create a php script that reads a list of urls and insert them in a mysql-database. The problem is that it inserts only the first line and then stops.
<?php
$conn=mysql_connect("my_servername","my_username","my_password") or die (mysql_error());
mysql_select_db("my_dbname") or die (mysql_error());
$url = array("url1.csv",
"url2.csv",
"url3.csv",
.
.
.
"url15.csv",
);
for ($i=0; $i<15; $i++)
{
$url_go = file_get_contents($url[$i]);
$z = array_filter(explode("\x0A",$url_go[$i]));
$counter=0;
foreach($z as $k=>$v)
{
if($metr>2)
{
$y=( (explode(';',rtrim($v,";"))) );
$sql = 'INSERT INTO `mysql_table_name` (name_of_column_1,name_of_column_2, name_of_column_3, name_of_column_4, name_of_column_5, name_of_column_6,name_of_column_7,name_of_column_8,name_of_column_9,name_of_column_10,name_of_column_11,name_of_column_12,name_of_column_13, name_of_column_14,name_of_column_15, name_of_column_16)
VALUES ('.$y[0].', '.$y[1].', '.$y[2].', '.$y[3].', '.$y[4].', '.$y[5].', '.$y[6].', '.$y[7].', '.$y[8].', '.$y[9].', '.$y[10].', '.$y[11].', '.$y[12].', '.$y[13].', '.$y[14].' , '.$y[15].')';
}
$counter++;
}
}
$result=mysql_query($sql) or die('Query failed:' . mysql_error());
mysql_close($conn);
?>
Database has been created with navicat. The urls are in a csv type.Like a table with the same columns as the columns of my database but i dont want to insert the first 3 rows of csv-urls
Upvotes: 0
Views: 72
Reputation: 6642
Your query execution needs to be within your 2nd for loop because the $sql variable keeps getting overwritten and only executed 1 time.
$sql = 'INSERT INTO `mysql_table_name` (name_of_column_1,name_of_column_2, name_of_column_3, name_of_column_4, name_of_column_5, name_of_column_6,name_of_column_7,name_of_column_8,name_of_column_9,name_of_column_10,name_of_column_11,name_of_column_12,name_of_column_13, name_of_column_14,name_of_column_15, name_of_column_16)
VALUES ('.$y[0].', '.$y[1].', '.$y[2].', '.$y[3].', '.$y[4].', '.$y[5].', '.$y[6].', '.$y[7].', '.$y[8].', '.$y[9].', '.$y[10].', '.$y[11].', '.$y[12].', '.$y[13].', '.$y[14].' , '.$y[15].')';
mysql_query($sql) or die('Query failed:' . mysql_error());
Upvotes: 1
Reputation: 2300
First off, pay attention to the comment by @tadaman about the obsoleteness of mysql() functions and the need to properly escape data to avoid SQL injection.
The reason you only get one entry in the DB is because your mysql_query statement is not inside the loop, so only the last $sql variable is actually being passed to the mysql_query call, which is only being run once.
Upvotes: 0