简体   繁体   中英

PHP not Inserting into MySQL database all statements are there

I was wondering if anyone had input as to why this statement isn't inserting into my MySQL database. It's not showing any errors and when I enter the SQL statement in manually it inserts the info.

<?php

$host="mysql16.000webhost.com";
$user_name="a1611480_akaash";
$pwd="*****";
$database_name="a1611480_akaash";
$db=mysql_connect($host, $user_name, $pwd);

$sql = "INSERT INTO mydata VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";

mysql_query($sql);

?>

This is due to the fact that mysql does not know which database to use for this SQL statement. Include mysql_select_db .

mysql_select_db($database_name);

To get any type of error in php (except fatals) enclose your code with a try block

try{
    // db code
}catch(Exception $e){
    // something is wrong
    echo "Oh God! I got this ". $e->getMessage();
}

To see the error do this:

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

And from your query i am assuming that you have one column and you want to add multiple values So this maybe the format:

$sql = "INSERT INTO mydata VALUES 
        ('dude1'), ('dude2'), ('dude3'), ('dude4'), ('dude5);";

That's because you don't mention the column names - see http://www.w3schools.com/php/php_mysql_insert.asp Also you forgot to select the database - mysql_select_db("my_db");

So your query would have to be something like "INSERT INTO mydata (column1, column2, column3, column4, column5) VALUES ('dude1', 'dude2', 'dude3', 'dude4', 'dude5')";

Edit: Of course Corey is right. It's just a better practice I think - I always do it :)

You are connecting to a remote host, are you sure you have the rights to do so? Where is this code executed?

Outputting the result of mysql_error() would be useful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM