do734 do734 - 1 month ago 11
MySQL Question

Mysql configured correctly for remote connection but php code failing connection?

I went through the grueling process of figuring out how to bind the correct address in the config file and connect mysql to my remote server. Yesterday it was working with different code and now it's not connecting. I'm getting the die "connection failed: " but its not showing me the connect_error as I called for so cant even figure out the issue? Does anyone see something wrong with my code? NOTE: I know this is unsafe and I usually do prepared statements but just trying to work with connection to the db issue now.

<?php
$server = "174.---.--.187";
$username = "dylanto";
$pass = "------";
$db = "survey";
//$port = 3306;
//create connection
$conn = new mysqli($server, $username, $pass, $db);
//check connection
if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}

$user = $_POST['user'];
$pass = $_POST ['pass'];

$sql = "insert into login (user, pass) values ('$user','$pass')";

if ($conn->query($sql)==TRUE) {
echo "Account created";}

else {echo "something went wrong";}
$con->close;
?>


Html code:

<html><head><title>Log-in</title>
<link rel="stylesheet" type="text/css" href="sytle.css"></head>
<body>
<center><u><strong><h2>Login</h2></u></strong></center>
<br />
<center>
<form action="signup_process.php" method="POST">
Pick Username: <br>
<input type ="text" name = "user"><br>
Pick Password:<br>
<input type ="password" name ="pass"><br>
<input type="submit" name="submit" value="Sign-up">
</form></center>
</body>
</html>

Answer Source

From

if (!$conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

To:

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Since if ($conn->connect_error) = If any error and if (!$conn->connect_error) if no error.

For prepared statement :

From:

$sql = "insert into login (user, pass) values ('$user','$pass')";

if ($conn->query($sql)==TRUE) {
echo "Account created";}

else {echo "something went wrong";}

To :

//sanityze POST
$user = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['user'], ENT_QUOTES, 'UTF-8')));
$pass = trim(mysqli_real_escape_string($conn, htmlspecialchars($_POST['pass'], ENT_QUOTES, 'UTF-8')));

//use prepared

$stmt = $conn->prepare("insert into login (user, pass) values (?,?)");

//bind parameter
$stmt->bind_param("ss", $user, $pass)

 $stmt->execute();

//then check