Tuesday 4 September 2018

MySQL query in PHP does not work

I've used this code with a different host with no difficulties. I'm trying to use this on a new host and it's not working. I am connecting to the database for sure, and the memberid is definitely in the table.

The server is running PHP 5.4 Can anyone see a problem with this code?
Any help is appreciated.
<?php
include("../../connection.php");

if ($_POST) {
    $memberid = $_POST["memberid"];
    $memberid = mysqli_real_escape_string($connection, $memberid);
    $query = "SELECT * FROM members WHERE memberid = '{$memberid}'";
    $result = mysqli_query($connection, $query);
    if (mysqli_num_rows($result) >= 1) {
        header("Location: www.example.com");
    }   else {
        header("Location: www.example.com");
    }
  }
?>

Here's the connection code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$connection = mysqli_connect($servername, $username, $password);
mysqli_select_db ("database_name");
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>


Your problem is here:
$connection = mysqli_connect($servername, $username, $password);
mysqli_select_db ("database_name");

With MySQLi rather than MySQL, you need to add the database name in with the connection details, so rewrite it as:
  $connection = mysqli_connect($servername, $username, $password, "database_name");

And this should work correctly for you now, what was happening previously was that your connection was ok but no database was being specified, now you have the database specified on the same mysqli_connect call so the PHP knows where to put/take the data .

0 comments:

Post a Comment