-2

I'm making a simple script installation, in which the user enters the page, the system tables are created. The SQL code for these tables are in the same directory that I access via the file_get_contents function, and then set to mysql_query.

But always get an error. I do not understand it because when I run the code by phpMyAdmin for example, it goes without any problem. What can it be?

PHP

   $sql = file_get_contents("install.sql");
   mysql_query($sql) or die("Error: ".mysql_error());

SQL

   DROP TABLE IF EXISTS `jogos`;
   CREATE TABLE `jogos` (
   `id` int(15) NOT NULL AUTO_INCREMENT,
   `casaid` varchar(255) NOT NULL,
   `foraid` varchar(255) NOT NULL,
   PRIMARY KEY (`id`)
   ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Error

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

    'CREATE TABLE `jogos` (
    `id` int(15) NOT NULL AUTO_INCREMENT,
     `casaid` varc' 

at line 2


Thanks in advance.

EDIT:

Thanks Joel and Florian for explaining. I do not really know about MySQLi, anyway, a solution that did not need to use the extension. For those who need it:

$sqls = ""; // here go your all sql's
$split_sqls = explode(";", $sql);
for($index = 0; $index < count($split_sqls) - 1; $index++) {
    $query = mysql_query($split_sqls[$index]);
if(!$query)
    die("Error at $index SQL.\n\n".mysql_error());
}

Regards!

Edmundo Santos
  • 8,006
  • 3
  • 28
  • 38
  • [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Phil Jan 21 '14 at 22:23

3 Answers3

2

Multiple queries are not supported in a single mysql_query. You'll have to use something that does support it - such as mysqli::multi_query. Learning mysqli or PDO will benefit you in the long run as well, since the mysql extension has been deprecated on good grounds.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
0

Multiple queries are not supported by the mysql_query() function. PHP5 has the mysqli_multi_query() function, which executes one or multiple queries which are concatenated by a semicolon.

$link = mysqli_connect("host", "user", "password", "database");

$query = file_get_contents("install.sql");
mysqli_multi_query($link, $query) or die("Error: ".mysqli_error($link));;

mysqli_close($link);

For further information look here.

Florian Bussmann
  • 436
  • 3
  • 10
0

Thanks Joel and Florian for explaining. I do not really know about MySQLi, anyway, a solution that did not need to use the extension. For those who need it:

$sqls = ""; // here go your all sql's
$split_sqls = explode(";", $sql);
for($index = 0; $index < count($split_sqls) - 1; $index++) {
    $query = mysql_query($split_sqls[$index]);
if(!$query)
    die("Error at $index SQL.\n\n".mysql_error());
}
Edmundo Santos
  • 8,006
  • 3
  • 28
  • 38