Job Gondwe Job Gondwe - 2 years ago 59
HTML Question

I am trying to run the code below but it gives me this error: Trying to get property of non-object in c:\xampp\htdocs\....\index.php on line 47

I am trying to execute below code but it gives me an error that 'trying to get property of non-object in c....' .
This code should pull up info about 'images' and 'texts' to be displayed on the index.php page. I have tried in all means but couldn't figure out what is the problem; I am a beginner in PHP by the way :) .I will appreciate if you please help me.

<!DOCTYPE html>

<?php
$alert = "";

//if upload button is pressed
if(isset($_POST['upload'])){
//the path to store the uploaded image
$target = "images/".basename($_FILES['image']['name']);

//connect to the database
$conn = new mysqli('localhost', 'imgcms', '', '');

//Get all the submitted data from thye form
$image = $_FILES['image']['name'];
$text = $_POST['text'];

$sql = "INSERT INTO images (image, text) VALUES ('$image', '$text')";


//Move the uploaded image into the folder: images
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$alert = "Image uploaded successfully";
}else{
$alert = "There was a problem uploading the image";
}

}



?>

<html>
<head>
<title>ImageBlogger</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="content">
<?php
//connect to the database to display image from the database
$conn = new mysqli('localhost', 'imgcms', '', '');
$sql = "SELECT * FROM images";
$result = $conn->query($sql);

if($result->num_rows > 0){
//output data of each row: image and text
while($row = $result->fetch_assoc()){
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."'>";
echo "<p>".$row['text']."</p>";
echo "</div>";
}
}else{
echo "0 results";
}
$conn->close();

?>

<form action="index.php" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">

<div>
<input type="file" name="image">
</div>

<div>
<textarea name="text" cols"40" rows="4" placeholder="Content..."></textarea>
</div>

<div>
<input type="submit" name="upload" value="Post the content">
</div>
</form>
</div>

</body>
</html>

Answer Source

Copying your code into an editor it looks like line 47 is;

if($result->num_rows > 0)

Before this line add the following and see if you get an error.

if (!$result) {
 echo 'Query Error is: ' . $conn->error;}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download