Trying to get property of non-object: Using SELECT - php

I got little problem with my code... because I try to SELECT sth from database and then INSERT some value to another table, but in normal code from w3school
and I got error
Tryingo to get property of non-object
Here is my code:
<?php
session_start();
function connectionDB(){
$host = "localhost";
$username = "root";
$password = "";
$db_name = "project";
$conn = new mysqli($host, $username, $password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function getID(){
$id = $_GET['id'];
return $id;
}
$login =$_SESSION['login'];
$conn =connectionDB();
$idCar = getID();
echo $idCar;
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
if($result->num_rows > 0)
$result = $conn->query($sqluser);
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";
?>
THIS IS THE CODE OF SIDE WITH PRODUCT

Please see change near your IF loop
$sqluser = "SELECT ID_USER FROM login_table WHERE LOGIN = $login";
$result = $conn->query($sqluser); //check result first
if($result->num_rows > 0) //get number of rows
{
while($row = $result->fetch_assoc())
{
$sql = "INSERT INTO cart (id_user) VALUES ('".$row['ID_USER']."')";
}
}else echo"error";

Related

PHP error: "Trying to get property of non-object"

I know this question has been asked alot of times earlier, but none of the other answers worked for me. I'm having trouble on this line:
$row = $conn->query("SELECT * FROM urls WHERE id = '$id'");
I followed a tutorial so I don't know if there is any other information that I should provide
EDIT:
heres the whole text document:
<?php
function idExists($id){
include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
$row = $conn->query("SELECT * FROM urls WHERE id = '.$id'");
if($row -> num_rows > 0){
return true;
} else {
return false;
}
}
function urlHasBeenShortened($url){
include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
$row = $conn->query("SELECT * FROM urls WHERE link_to_page = '$url'");
if($row->num_rows > 0){
return true;
} else {
return false;
}
}
function getURLID($url){
include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
$row = $conn->query("SELECT id FROM urls WHERE link_to_page = '$url'");
return $row->fetch_assoc()['id'];
}
function insertID($id, $url){
include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
$conn->query("INSERT INTO urls (id, link_to_page) VALUES ('$id', '$url')");
if(strlen($conn->error) == 0){
return true;
}
}
function getUrlLocation($id){
include $_SERVER['DOCUMENT_ROOT'] . '/short/includes/init.php';
$row = $conn->query("SELECT link_to_page FROM urls WHERE id = '$id'");
return $row->fetch_assoc()['link_to_page'];
}
?>
Init code
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
errors on lines: 7, 18
you did forget the database name :
$conn = new mysqli($servername, $username, $password);
// Create connection like this :
$conn = new mysqli($servername, $username, $password, $dbname);
change
$row = $conn->query("SELECT * FROM urls WHERE id = '$id'");
to
$row = $conn->query("SELECT * FROM urls WHERE id = ".$id);
also change :
if($row -> num_rows > 0)
to
if($row->num_rows > 0)

php echo result from mysql and datetime selection

MySQL database Start = "2017-03-29 01:30:00"
The problem is:
I print the $SQL and search the record in MySQL database, it can search the record. However, I need to debug and test if there is no result, it will be expected to echo "No". But, it always to echo "Yes" no matter I can get the record in MySQL or not.
How can I fixed it.
Main purpose: Get the record if there are and Echo "No" if there don't have record
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
if($result)
{
echo "Yes";
}
else{
echo "no";
}
?>
Mysql query only return fails if there is an issue, for successful execution it returns TRUE even if there is no record. You can achieve with follwing way
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$dbName = "fyp";
$tbName = "events";
$String_start = '2017-03-29 01:28:00';
$String_end = '2017-03-29 01:32:00';
$conn = new mysqli($serverName, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$staffID = $_SESSION['userID'];
$staff_ID = '15207800';
$sql = "SELECT *
FROM `$tbName`
WHERE `start` BETWEEN ('$String_start') AND ('$String_end')";
echo $sql;
$result=mysqli_query($conn,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows > 0)
{
echo "Yes";
}
else{
echo "no";
}
?>
Use mysqli_num_rows that will return total results returned by the query. If total > 0 then results found else no results.
To fetch rows from MySQL result set, use mysqli_fetch_assoc
$result = mysqli_query($conn,$sql);
// $result contains result set and will return `TRUE` if query was successfully executed
// and will return `FALSE` only in case of error
$total = mysqli_num_rows($result);
if($total > 0)
{
echo "Yes";
// Fetch rows from mysql result set
while($row=mysqli_fetch_assoc($result))
{
print_r($row);
}
}
else
{
echo "no";
}

PHP Loop through results

I am trying to loop through my database and check to see if the user already exists in another table. If they do then I want to increment a value, if they don't then I want to add the user.
When I run the code below it happily loops through all the results:
<?php
$servername = "p:10*********";
$username = "*******";
$password = "*******";
$dbname = "******";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM payroll WHERE user != ' ' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $result->num_rows;
while($row = $result->fetch_assoc()) {
$user = $row['user'];
$time = $row['time'];
$id = $row['id'];
echo $id;
echo $user;
}
} else {
echo "0 results";
}
$conn->close();
?>
However when I add in the SQL to check to see if they exist in the other table the loop no longer functions correctly and echos the same user each time.
<?php
$servername = "*******";
$username = "******";
$password = "********";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM payroll WHERE user != ' ' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $result->num_rows;
while($row = $result->fetch_assoc()) {
$user = $row['user'];
$time = $row['time'];
$id = $row['id'];
echo $id;
echo $user;
// Added existing user check:
$sql = "SELECT * FROM smsreport WHERE user = '$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "found";
} else {
echo "USER NOT FOUND";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
In the open eye:
Rename the inside $result variable. It is over writting the first $result.
It could be the problem. Not tested though.

PHP for Looping MySql id

I am Using Below Code to First Fetch all 'id' from MySql table.
<?php
$servername = "localhost";
$username = "**";
$password = "**";
$dbname = "**";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$slug = $_GET["category"];
$sql = "SELECT * FROM table WHERE category = '1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$dealid = $row["dealid"];
}} else {}
$conn->close();
?>
$dealid should return with all id's but it is returning with only 1.
Now below code is to show data with those id's:-
<?php
$num_rec_per_page=52;
mysql_connect('localhost','**','**');
mysql_select_db('**');
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM table2 WHERE id = $dealid ORDER BY id DESC LIMIT $start_from, $num_rec_per_page";
$rs_result = mysql_query ($sql);
while ($row = mysql_fetch_assoc($rs_result)) {
?>
<?php include( $_SERVER['DOCUMENT_ROOT'] . '/includes/dealbox.php' ); ?>
<?php
};
?>
But its only showing 1 data because returning id is only 1. I am not able to understand what the issue is. Any help is appreciable and will gift if someone help me out with this issue.
Dear friend all Id's are set into one array and return that array,
eg:
while ($row = mysql_fetch_assoc($rs_result))
{
$dealid[]= $row['id']; //array creation
}
and
return ($dealid);

PHP Database output. Arrays

In first case, i will get full array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row[header];
}
}
mysqli_close($conn);
?>
In the second case, i will get just 1st value from array:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test.com";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM articles WHERE writer='$w_name' ";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$q=$row[header];
}
}
mysqli_close($conn);
?>
<div>
<? echo $q ?>
</div>
What should I do, to make 2nd case work like 1st? I mean, how to put into $q, all values of array, not just the first.
You are not defining $q as an array at all.
$q=array();
...
while ($row = mysqli_fetch_assoc($result)) {
$q[]=$row['header'];
}
...
an example of output :
foreach($q as $header) {
echo $header.'<br>';
}
You are overwriting $q . Try using $q[]=
change $q=$row[header]; line to $q[]=$row[header];
and then not echo $q; but print_r($q);
Try to change this into the while
$q = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
array_push($q, $row['header']); // i guess header is a column of the table
}
}
and then you must have your array when print the $q variable, i mean do an print_r($q)
More info about array_push: http://php.net/manual/es/function.array-push.php
Hope this helps :)

Categories