0

I need to search through a MYSQL table for any string that may or not be in a row and print it out on screen. I could easily do this with python but I am still learning PHP and it's way different and am unfamiliar with how it's done here.

The row have multiple sets of words separated by commas so I need to use LIKE for any word that matches $string

$string = 'text';
$db = mysqli_connect("localhost", "root", "", "data");
$result = mysqli_query("SELECT row FROM table WHERE row LIKE '%$string%'");
if($string == $result){
    echo "String found";
}else{
    echo "No string found!";
}
9
  • What is the problem you're running into with this? Are you just trying to understand how to execute a query and work with the response in PHP? Your query looks fine (except for the SQL injection potential - look into parameterized queries with mysqli). The problem with your code is that $result will contain the result object, and not the actual result value. Commented Jul 20, 2018 at 21:38
  • I'm going to guess that $result may be something like "some text" and that is not == $string which is "text". This is because database returns "like" results Commented Jul 20, 2018 at 21:41
  • Why not just query for SELECT row FROM table WHERE row = '$string'? Commented Jul 20, 2018 at 21:44
  • 1
    @ScarletHarlot You should use FIND_IN_SET(). See stackoverflow.com/questions/28639692/… Commented Jul 20, 2018 at 21:56
  • 1
    You also need to read a tutorial on how to use mysqli. You're missing the connection argument, and you need to call mysqli_fetch_assoc() to get the rows of results. Commented Jul 20, 2018 at 21:57

1 Answer 1

0

Found here.

You need to iterate over the result's cursor returned by query() like so:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
Sign up to request clarification or add additional context in comments.

Comments