I've been trying to find a solution, I've found some similar issues but nothing seems to tell exactly how to fix it.
<?php
$connect = mysql_connect("localhost", "root", "test") or die("Couldn't connect!");
$connectdb = mysql_select_db("test") or die("Couldn't connect to database!");
echo "Connection established to Database.";
$sql = "INSERT INTO hell (name, age) VALUES ('Josh',17)";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
this returns:
Connection established to Database.
Fatal error: Call to a member function query() on resource in C:\\xampp\\htdocs\\php\\connect-database.php on line 8
I'm using a slightly changed version from http://www.w3schools.com/php/php_mysql_insert.asp
Could someone provide me the documentation to fix this or fix the code?
Use:
if (mysql_query($sql) === TRUE) {
instead of
if ($connect->query($sql) === TRUE) {
And please use mysqli or PDO
This should help:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
if ($result = $mysqli->query("INSERT INTO hell (name, age) VALUES ('Josh',17)")) {
printf("New record created successfully\n");
/* free result set */
$result->close();
}
PS: It's recommended to use mysqli instead mysql extension.
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.