Home > database >  How to Select multiple queries in PHP to MySQL
How to Select multiple queries in PHP to MySQL

Time:10-26

This query works when I run in MySQL:

SELECT * FROM `table` WHERE `ip` LIKE '1.1.1.1';
SELECT * FROM `table` WHERE `ip` LIKE '2.2.2.2'

But when I run this PHP code, it does not work:

<?php
require('configuration.php');

// Create connection
$conn = new mysqli($db_host, $db_username, $db_password, $db_name);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$query = "SELECT * FROM `table` WHERE `ip` LIKE '1.1.1.1';
SELECT * FROM `table` WHERE `ip` LIKE '2.2.2.2'";

$sql = $query;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    echo "ID: " . $row["id"]. "<br>IP:" . $row["dedicatedip"]. "<br><br>";
  }
} else {
  echo "0 results";
}
$conn->close();

This is the error I see in Apache:

PHP Notice:  Trying to get property 'num_rows' of non-object in /home/user/connect.php on line 17

To clarify, line 17 starts with:

if ($result->num_rows > 0) {

I do not know PHP a lot, but I tried to solve by searching but I failed.

CodePudding user response:

You can resolve the problem with Mysql UNION statement.

$query = "(SELECT * FROM table WHERE ip LIKE '1.1.1.1') UNION (SELECT * FROM table WHERE ip LIKE '2.2.2.2')";

CodePudding user response:

There is no need for a UNION statement. This also works:

SELECT * FROM table WHERE ip IN ('1.1.1.1', '2.2.2.2')
  •  Tags:  
  • php
  • Related