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

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)

Related

Calling PHP function from external PHP file

I've recently started learning functional programming in php, I can't figure out why isn't this working.
I have a separate file called 'functions.php' and I'm trying to call a function in it from index file.
functions.php:
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->
}
}
function displayPublic() {
connectSql();
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}
index.php:
include 'functions.php';
displayPublic();
you are not returning the $conn
try
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->connect_error);
} else {
return $conn;
}
}
function displayPublic() {
$conn = connectSql();
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}
or make $conn a global variable
<?php
$conn;
function connectSql() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
global $conn;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Yhteys katkesi: " . $conn->connect_error);
}
}
function displayPublic() {
connectSql();
global $conn;
$sql = "SELECT * FROM projects WHERE public == true ORDER BY dateStarted DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()){
echo "Project found";
}
} else {
echo "Ei tuloksia";
}
$conn->close();
}

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.

Trying to get property of non-object: Using SELECT

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";

how to replace current_date() to any date type by user

how to replace current_date() to any date type by user
example:
www.example.com/2025-01-04
or any date
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = current_date() ";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
Try this:
<?php
$servername = "localhost";
$username = "11_11";
$password = "1Eh]V";
$dbname = "1_1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_GET['date'])
and preg_match('/^\d{4}(-\d{2}){2}$/', $_GET['date']) // primitive validation
) {
$date = $_GET['date'];
} else {
$date = date('Y-m-d');
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
$stmt->bind_result($domain);
$data = array();
while ($stmt->fetch()) {
$data[] = array('domain' => $domain);
}
$conn->close();
$smarty = new Smarty;
$smarty->assign('data', $data);
$smarty->display(APP_THEME . '/dom.tpl');
I would recommend using a prepared statement here (assuming you are using mysqli).
A) Because you can dynamically assign either current_date() or variable using user input value to a placeholder.
B) The prepared statement would make this operation more secure since you are escaping all user input.
if (!empty($_POST['date'])) {
$user_date = $_POST['date'];
} else {
$user_date = "current_date()";
}
$sql = "SELECT domain FROM insights_base WHERE domain_1 = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $user_date);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
Depending on how you are getting the date from user, you may need to validate it to make sure that it is in the proper date/time format for mysql.

Categories