-1

I just want to select and display data from a database. I think I am following all the tutorials etc. online but something is wrong. My code:

<?php

$user = 'root';
$pass = 'root';
$db='test';
$host ='localhost';
$name = 'ryan';


$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}
    else{
        echo 'Checkpoint 1 <br>';
    }

$sql = "SELECT * FROM user WHERE name LIKE ryan";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
echo'checkpoint 2';
$row = $result->fetch_assoc();
echo'checkpoint 3';
?>

I can get to 'checkpoint 2' but for some reason the fetch_assoc() function does not do anything. I am using Netbeans, and the fetch_assoc() does not even turn green as the num_rows function does. fetch_assoc does turn green if I remove both parentheses at the end.

ratrace123
  • 976
  • 4
  • 12
  • 24

5 Answers5

1

Your mysql query syntax is wrong.
LIKE takes a pattern, by not enclosing it in quotes, you basically provided a column name

Change your query like this

SELECT * FROM `user` WHERE `name` LIKE 'ryan';

Also add some error handling for the query

$result = $mysqli->query($sql) or die(mysqli->error);
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
0

Try this query:

$sql = "SELECT * FROM user WHERE name LIKE 'ryan'";
RaisoMos
  • 159
  • 4
  • 11
0

You have to bind your like statement as

$param = "%ryan%";
$result = $mysqli->prepare("SELECT * FROM user WHERE name LIKE ?");
$result->bind_param("s", $param);
$result->execute();
$num_results = $result->num_rows;
$row = $result->fetch_assoc();
Saty
  • 22,443
  • 7
  • 33
  • 51
0
<?php

$user = 'root';
$pass = 'root';
$db='test';
$host ='localhost';
$name = 'ryan';


$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}
    else{
        echo 'Checkpoint 1 <br>';
    }

$sql = "SELECT * FROM user WHERE name LIKE 'ryan'";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
print_r($num_results);exit;
echo'checkpoint 2';
$row = $result->fetch_assoc();
echo'checkpoint 3';
?>
Drudge Rajen
  • 7,584
  • 4
  • 23
  • 43
0

You can use string input with LIKE statement by using the quotes and % sign.

Modified Code:

$sql = "SELECT * FROM user WHERE name LIKE '%ryan%'";
$result = $mysqli->query($sql);
$num_results = $result->num_rows;
$row = $result->fetch_assoc();

What i have changed?

  1. Add single quotes inside the double quote for input string.
  2. Add % sign at start and end for matching type both
devpro
  • 16,184
  • 3
  • 27
  • 38