MySQL query in PHP not working

I have used this code with a different host without any difficulty. I am trying to use this on a new host and it doesn't work. I am connecting to the database exactly and the member is definitely in the table.

The server is running PHP 5.4 Can anyone see the 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";
?>

      

+3


source to share


2 answers


Your problem is here:

$connection = mysqli_connect($servername, $username, $password);
mysqli_select_db ("database_name");

      

In MySQLi, not MySQL, you need to add the database name along with the connection details, so rewrite it as:



  $connection = mysqli_connect($servername, $username, $password, "database_name");

      

And now this should work correctly for you, what happened before was that your connection was ok but no database specified, now you have the database specified in the same call mysqli_connect

, so PHP knows where put / take data.

+3


source


<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$memberid = $_POST["id"];
$memberid = mysqli_real_escape_string($connection, $memberid);
$query = "SELECT * FROM `members` WHERE memberid= '$memberid'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) { 
echo "Success";
}   else {
echo "Error";
}
}
?>

      

Connection code:



<?php

$servername = "localhost";
$username = "username";
$password = "password";
$connection = mysqli_connect($servername, $username, $password, database_name);
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}else{
    echo "Connected successfully";
}

?>

      

0


source







All Articles