-1

I get this error message

Notice: Trying to get property of non-object in C:\wamp64\www\MatchManagement\MatchPopulate.php on line 20

Can anybody tell what is wrong with the code?

<?php 
/* Need to correct this code*/
require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
$Already = False;

$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = $uOpponentName AND Venue = $uVenue";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data  ELSE add match to database
    if ($result->num_rows >0) {
        while($row = $result->fetch_assoc()) {
            $OpponentName = $row['Opponents'];
            $selected = 'selected="selected"';    
        } 
    } else { 
        $sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
     }
$conn->close();
?>
ndmeiri
  • 4,979
  • 12
  • 37
  • 45
DaveTheGolfer
  • 39
  • 1
  • 8

2 Answers2

0

You're missing single quotes in your query. So $result is false and $result->num_rows fail.

$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";

NB: Your code is vulnerable to SQL injections and may compromise the security of your database. You should have a look to parameterized queries function.

Finally, you should ever test the result of function before to use it. ex:

$result = $conn->query($SQL);
if (!$result) {
    // error
} else {
    if ($result->num_rows >0) {
       // ...
    }
}
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • #Syscall Thanks for the advice.As stated earlier I am still a novice. I am trying to get the basic code working before advancing to a more secure version. The code is on my desktop and laptop only at present. Still struggling to get my head around having both a server and a browser to contend with. I have only coded in VBA or VB.net before. – DaveTheGolfer Feb 17 '18 at 10:18
0

The error occurs when you try to access a property of an object that isn't an object. In this case you cannot access the property, as the $result isn't an object. It is a boolean = false. One thing is to check that a variable is an object using PHP's is_object. This doesn't answer the issue with you query, but rather the question about the error itself.

So for example, using is_object to fail early,

if (is_object($result) && $result->num_rows >0) {}

Similary you could do,

if ($result !== false && $result->num_rows >0) {}
user9189147
  • 296
  • 1
  • 7