MySQL query is giving the error but it seems to me that table name in data_new
only and columns are same as written
This is the SQL Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0573','cate-csir','NKN')' at line 1"
<?php
$fm = fopen('main.txt','r');
@mysql_connect('localhost','root','');
@mysql_select_db('username');
$count=0;
while ($line = fgets($fm)) {
$new_data=@split(':',$line);
$query="INSERT INTO `data_new` (`directory`,`machineip`,`description`,`state`,`status`,`instituteid`,`category`,`project`) VALUES ('$new_data[0]','$new_data[1]','$new_data[2]','$new_data[3]','$new_data[4],'$new_data[5]','$new_data[6]','$new_data[7]')";
}
$result=@mysql_query($query);
if(!$result){
die(mysql_error());
}
fclose($fm);
?>
You have a missing '
after $new_data[4] in the insert command:
...'$new_data[4],'$new_data[5]'...
^
|
here
Just a note: MySQL extension has been deprecated long time ago and has been removed from php as of v7. Use mysqli or pdo instead.
You have 2 obvious errors one syntactic error and one logic error
First a missing quote after '$new_data[4]
in the VALUES clause
Second you are only issuing the last query you build i.e. after the loop has completed. That will only INSERT the last line of your input file to the database.
<?php
$fm = fopen('main.txt','r');
// its also a good idea to check your connection worked before proceeding with any more code
$link = mysql_connect('localhost','root','');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('username');
$count=0;
while ($line = fgets($fm)) {
$new_data=@split(':',$line);
// a missing single quote after'$new_data[4]
$query="INSERT INTO `data_new`
(`directory`,`machineip`,`description`,
`state`,`status`,`instituteid`,
`category`,`project`)
VALUES ('$new_data[0]','$new_data[1]','$new_data[2]',
'$new_data[3]','$new_data[4]','$new_data[5]',
'$new_data[6]','$new_data[7]')";
// and the query must be executed inside the loop
$result = mysql_query($query);
if(!$result){
die(mysql_error());
}
}
//$result=@mysql_query($query);
//if(!$result){
// die(mysql_error());
//}
fclose($fm);
?>
I have to mention Every time you use the
mysql_
database extension, a Kitten is strangled somewhere in the world it is deprecated (gone for ever in PHP7) Specially if you are just learning PHP, spend your energies learning thePDO
database extensions. Start here its really pretty easy