I'm new to most of this, but I'm trying to simply insert some information into my new database in phpmyadmin through php code. Here is the code I'm using to connect (dbh.inc.php)
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 8889;
$link = mysqli_init();
$conn = mysqli_real_connect(
$link,
$host,
$user,
$password,
$db,
$port
);
?>
And here is the code i'm using to connect and insert
<?php
include_once 'includes/dbh.inc.php';
$name = $_POST['mName'];
$email = $_POST['mEmail'];
if($conn)
echo "Connected <br/>";
else
{
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
}
if(isset($_POST['mName']))
echo $name.'<br/>';
if(isset($_POST['mEmail']))
echo $email.'<br/>';
$sql = "INSERT INTO userinfo (_email, _name, _date) VALUES ('$email', '$name', '2018-6-23 11:20:01')";
echo "Query = " . $sql.'<br/>';
if(mysqli_query($conn,$sql))
echo 'It Worked!';
else
{
echo "Error: " . mysqli_error($conn);
}
?>
Here's a picture of my phpmyadmin database with one test entry
and finally, here's what I get when trying to run this code:
As you can see, I connect to the database just fine, and then I hit my "Error:" line after trying to insert information, but nothing prints, and nothing is added to my phpmyadmin database. I'm using MAMP.
Does anyone have any ideas as to why this is happening? Let me know if additional info is needed.
Thank you so much :)
You are checking the wrong variable for your mysqli_error()
. mysqli_real_connect()
returns a boolean and mysqli_error()
requires the result of mysqli_init ()
or mysqli_connect()
.
// change
echo "Error: " . mysqli_error($conn);
// to this
echo "Error: " . mysqli_error($link);