I feel like I'm getting closer to figuring out why PHP is not saving data to my database. I've tried learning PHP and MySQL from numerous tutorials and all have failed me.
So... I feel like there may be something that I haven't been specifying when trying to connect to a MySQL database.
In a recent tutorial that simply outputs text from an input to a table in MySQL, I got an Error stating that the server "localhost" was not found.
My Apache has been installed on port 60 (not the default port 80). So I figured that that might be the problem. I tried adding localhost:60 to the mysqli_connect rather than localhost itself and the error disappeared!
There is still a problem though: 1. It takes forever to load the demo.php page (see code below). 2. The data still isn't being added....
Here is the code (I converted it from the original MySQL on the video, to MySQLi and added comments):
demo.php:
<?php
define('DB_NAME', 'forms1');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost:60');
// stored in a variable to TEST if it's working
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_HOST);
// TEST if a link has been established (connection)
if (!$link) {
die('Could not connect:' . mysqli_error($link));
}
// same as above
$db_selected = mysqli_select_db($link,DB_NAME);
if(!$db_selected) {
die('Can\t use ' . DB_NAME . ': ' . mysqli_error($link));
}
// Check SUCCESS with commented command below
// echo 'Connected successfully.';
// stored in a variable to shorten
$value = $_POST['input1'];
// stored in a variable to TEST
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
if(!mysqli_query($link, $sql)) {
die('Error: ' . mysqli_error($link));
}
mysqli_close($link);
?>
demo-form.php:
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="input1" /></p>
<input type="submit" value="Submit" />
</form>
I've also had the same problem with another code, see the thread here: PHP database won't save data
I really hope that someone can help me here. It's a shame that I haven't even gotten the basis to work yet...
Thanks!
mysql_errortomysqli_erroryou're mixing SQL functions which, well... don't "mix". ;-)$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_HOST);to$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);you're repeatingDB_HOST