Friday, 14 March 2014

PHP - Problem with "mysqli" - SQL Database

SQL works in phpmyadmin not in PHP



If your sql code works in phpmyadmin not in php probably main reason for that is in "mysqli" procedure.

"MYSQLi" don't work with "old" version's of PHP so you will not get any error everything will seem fine but nothing will happen.

You are probably connecting to database something like this:

$con=mysqli_connect("host","admin","password","name_of_database");

if (mysqli_connect_errno()) {
       echo "Error, we can't connect to database: " . mysqli_connect_error();
} else {
$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');
}

if (!mysqli_query($con,$sql)) {
    echo "Error!";
} else {
    echo "Ok!";    
}
mysqli_close($con);  // we need to close connection to database...

And something is wrong but you don't know what?

Try the same code just with "mysql" function and it will work, so you will need to write something like this:

$sql="INSERT INTO userTable (username, password) VALUES ('$username', '$password');

mysql_connect("host", "admin", "password") or die(mysql_error()); 

mysql_select_db("name_of_database") or die(mysql_error()); 

$data = mysql_query($sql) or die(mysql_error());

 mysql_close();

When I write my code like this, magic happen, my user is inserted to database...

Notice!
"or die(mysql_error())" will make your server to "die" so you will get error and everything will stop if you need to continue just remove that and everything will be ok.

If this little "tutorial" helped you, please subscribe, like us on facebook, share it, or do whatever you want with it. :)

Have a good one. M.L.



No comments:

Post a Comment