0

I want to return $contact_id but all I get is :

success.
the user id is

For example, in my insert.htm I enter $CheckContact : enter image description here

It should be returning : the user id is 11. This is my user table :

enter image description here

And if I click checkcontact.php again in my browser address bar then I get :

the user id is 23

It's always 23, no matter what $CheckContact is. Can you tell me what is wrong ? Here is my code :

<?php

require('dbConnect.php');

$CheckContact = $_POST['phonenumber'];
$sql = "SELECT * FROM user WHERE username = '$CheckContact'";
$result = mysqli_query($con, $sql);
$check = mysqli_fetch_array($result);
//if $CheckContact is in the user table...
if(isset($check)) {

    echo 'success.' . "<br>";

    // get the associated rows of $CheckContact
       $row = mysqli_fetch_assoc($result);
    // get the associated user_id in that row

       $contact_id = $row["user_id"];
       echo "the user id is ", $contact_id;

} 
//if $CheckContact is NOT in the user table...
else {

    echo 'failure';
    }

?>
Doruk Ayar
  • 334
  • 1
  • 4
  • 17
CHarris
  • 2,693
  • 8
  • 45
  • 71
  • 1
    Have you switched on error reporting in PHP? – KIKO Software Apr 16 '17 at 07:52
  • 1
    Can you share your form from insert.htm? – f_i Apr 16 '17 at 07:53
  • This Problem can occur, in a case when your query fails. `$check` would be null and it is passing the check of `isset` because it is set now. instead use `!empty` – Sahil Gulati Apr 16 '17 at 07:55
  • 2
    [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe. – junkfoodjunkie Apr 16 '17 at 08:13
  • @FaizKhan insert.htm isn't the issue I am quite sure as I am getting success. – CHarris Apr 16 '17 at 08:50

2 Answers2

2

When I change my code to :

<?php

require('dbConnect.php');

$CheckContact = $_POST['phonenumber'];
$sql = "SELECT * FROM user WHERE username = '$CheckContact'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);

if($num_rows >= 1) {

 etc....

It works ok.

CHarris
  • 2,693
  • 8
  • 45
  • 71
0
 why dont you use this:
<?php
$sql="Select query";
               $result=mysqli_query($con,$sql);
                while($rws=mysqli_fetch_assoc($result)){
                ?>
to print all data
<?php 
}
?>

try empty() for $check this will indicate whether the variable contains null values or not