-2

I am trying to work with databases on PHP, however I am getting an error when I try to make a table of data. The table seems to be created correctly (I think) but when I want to print the confirmation of the table is created, it throws me an error. This is the code:

   if (mysql_query($connection,$sql)) //error
   {
      echo "1 record added";
   }
   else
   {
      die('Error: ' . mysql_error($con)); //error
   }

They both give me the error mysql_query() expects parameter 1 to be string and mysql_error() expects parameter 1 to be resource

Where $sql - the info being put in the table

Charles
  • 50,010
  • 13
  • 100
  • 141
user1404664
  • 71
  • 1
  • 2
  • 8
  • the error says that the function `mysql_query() expects parameter 1 to be string`. Are you sure that variables `$connection` and `$sql` are string? – Vainglory07 Feb 17 '14 at 01:39
  • thats backwards, parameters should be: `($sql,$connection)` –  Feb 17 '14 at 01:39
  • 1
    Why is it called `$connection` first` and `$con` second? And why didn't you just try switching parameter order for the first? Isn't the error message clear? – mario Feb 17 '14 at 01:39
  • 1
    You are calling `mysql_query()` like `mysqli_query()`, which takes a resource as its first param. – Michael Berkowski Feb 17 '14 at 01:39
  • 1
    Are people still using `mysql` functions? Please, get with the times and use `mysqli` or `pdo`. – Christian Feb 17 '14 at 01:40
  • [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Phil Feb 17 '14 at 01:52
  • First thing I noticed @MichaelBerkowski – Funk Forty Niner Feb 17 '14 at 02:50

2 Answers2

1

That won't work because mysql_query only returns a boolean based on if the query failed to execute or not (i.e. SQL syntax error).

You'll need to use mysql_affected_rows instead.

mysql_query($sql);
if(mysql_affected_rows()) {
    echo "1 record added";
}

Please take note of the scary red box on that page. mysql_query is deprecated. You need to switch to mysqli

Phil
  • 141,914
  • 21
  • 225
  • 223
Machavity
  • 29,816
  • 26
  • 86
  • 96
0
$server = 'localhost';  
$username   = 'root';  
$password   = 'YOUR PASSWORD';  
$database   = 'DB_name';  
$con = mysql_connect($server, $username,$password);
$db = mysql_select_db($database);
if(!$con)  
{  
    exit('Error: could not establish database connection');  
}  
if(!$db)  
{  
    exit('Error: could not select the database');  
} 
$sql ="CREATE TABLE Persons(FirstName CHAR(30),LastName CHAR(30),Age INT)";
$result = mysql_query($sql);
if (!$result) //error
   {
     echo mysql_error(); //error
   }
   else
   {
      echo "1 record added"; 
   }
Ana El Bembo
  • 1,787
  • 1
  • 12
  • 5