My page crashes when I try to retrieve information from MySQL - php

I'm having some issues with my PHP script.
I have a PHP function which is stored in a PHP file, and I'm trying to run that PHP function from another script.
So to explain myself with code:
like.inc.php:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `posts` WHERE `id` = '$id'");
while ( $row = $objQuery->fetch_object() ) {
if ( $row->count == 1 ) return true;
}
}
profile.php:
include ( 'like.inc.php' );
if (post_exists(70) === true) {
echo 'Exists!';
}
A post with ID 70 exists, so it should echo Exists! but instead it just crashes half of my page. So maybe it's not loaded correctly?
Any help would be highly appreciated!

Where you have $objQuery must by $query. Try with this code:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
$query = $connection->query("SELECT COUNT(`id`) AS `count` FROM `posts` WHERE `id` = '$id'");
while ( $row = $query->fetch_object() ) {
if ( $row->count == 1 ) return true;
}
}

You can write the function in a different way like so:
function post_exists($id) {
$host = "example";
$username = "example";
$password = "example";
$database = "example";
$connection = new mysqli($host, $username, $password, $database);
$id = $connection->real_escape_string($id);
// Instead of getting count, just get the row and
// do the count with PHP
$query = $connection->query("SELECT * FROM `posts` WHERE `id` = '$id' LIMIT 1");
if($query){
return $query->num_rows > 0;
}
return false;
}

Related

odbc_exec - no error or results

I'm new to using odbc functions. I'm trying to simply execute a simple query, but I get not error or results back. I'm not sure what's wrong.
$server = [hidden];
$database = [hidden];
$user = [hidden];
$password = [hidden];
$connection = odbc_connect("Driver={ODBC Driver 13 for SQL Server};Server=$server;Database=$database;", $user, $password);
if ($connection) {
$mail = 'email#email.com';
$queryc = "SELECT COUNT(*) AS [Found] FROM [Table].[dbo].[Persons] WHERE [Address] = '$mail'";
$resultsc = odbc_exec($connection, $queryc);
if( !$resultsc ) {
die( print_r( odbc_error())));
} else {
'hi!';
}
}
Figured out the problem. It was fixed doing this:
$server = [hidden];
$database = [hidden];
$user = [hidden];
$password = [hidden];
$connection = odbc_connect("Driver={ODBC Driver 13 for SQL Server};Server=$server;Database=$database;", $user, $password);
if ($connection) {
$mail = 'email#email.com';
$queryc = "SELECT COUNT(*) AS [Found] FROM [Table].[dbo].[Persons] WHERE [Address] = '$mail'";
$resultsc = odbc_exec($connection, $queryc) or die(odbc_errormsg());
if( $resultsc ) {
'hi!';
}
}

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

PHP Warning: mysqli_fetch_assoc() expects exactly 1 parameter, 3 given in

I get this error, I tried going through other similar threads but it didn't help.
here is php
$host = "http://www.example.net";
$hostname = "localhost";
$username = "aaa";
$password = "sss";
$userstable = "ddd";
$dbName = "fff";
if ($url != $host){
$con = mysqli_connect($hostname, $username, $password, $dbName);
//#mysqli_select_db("$dbName");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = mysqli_fetch_row(mysqli_query($con, "SELECT * FROM $userstable where(url = '$url')"));
if ($query == false){
$hits = "1";
$query2 = "INSERT INTO $userstable (url,hits) VALUES('$url','$hits')";
}
else {
$hitquery = "SELECT `hits` FROM $userstable where url = '$url'";
$result = mysqli_query($con, $hitquery);
$hits = mysqli_fetch_assoc($result, 0, 'hits');
//$hits = mysqli_result(mysqli_query("SELECT `hits` FROM $userstable where url = '$url'"), 0, "hits");
$query2 = "UPDATE $userstable SET `hits` = hits+1 where url = '$url'";
}
mysqli_query($con, $query2);
}
if(!$url) {
$url = "$host";
}
eror generate on line 157
$hits = mysqli_fetch_assoc($result, 0, 'hits');
How to fix this mysqli?
Syntax mysqli_fetch_assoc is:
array mysqli_fetch_assoc ( mysqli_result $result )
Try (for PHP >=5.4):
$hits = mysqli_fetch_assoc($result)['hits'];
From the codes, I see that you want to UPDATE the final records from hits.
$hitquery = "SELECT * FROM $userstable where url = '$url'";
$result = mysqli_query($con, $hitquery);
while(null !== ($hits= mysqli_fetch_assoc($result))) {
$query2 = "UPDATE $userstable SET `hits` = hits+1 where url = '$url'";
}

Having trouble pushing data from a sql query to an array for comparison

So I am trying to compare user input from a form with data from a database, first name, last name, and email. My problem has been comparing my results with the ones that the user put in. What I am trying to do is put the results from my query into an array and then compare each array item against the input of the user. Yet I can't get through my process. What am I doing wrong?
Thank you all in advance.
P.S. I am a php newbie so any suggestions would also be appreciated
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user
$firstname = $_POST['first'];
$lastname = $_POST['last'];
$email = $_POST['email'];
//query for the database to select the columns
$queryFirst = "SELECT firstname FROM users";
$queryLast = "SELECT lastname FROM users";
$queryEmail = "SELECT email FROM users";
//query results
$resultFirst = $conn -> query($queryFirst);
$resultLast = $conn -> query($queryLast);
$resultEmail = $conn -> query($queryEmail);
$firstResult = array();
$lastResult = array();
$emailResult = array();
array_push($firstResult, $resultFirst);
array_push($lastResult, $resultLast);
array_push($emailResult, $resultEmail);
$firstValid = mysqli_result::fetch_array($firstResult);
$lastValid = mysqli_result::fetch_array($lastResult);
$emailValid = mysqli_result::fetch_array($emailResult);
//comparing query results to user input
foreach($firstResult as $comp) {
if(strpos($firstname, $comp) !== false) {
$firstname = true;
} else {
return false;
}
}
foreach($lastResult as $comp) {
if(strpos($lastname, $comp) !== false) {
$lastname = true;
} else {
return false;
}
}
foreach($emailResult as $comp) {
if(strpos($email, $comp) !== false) {
$email = true;
} else {
return false;
}
}
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($firstname && $lastname && $email = true) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Okay so first thing as already told you andrewsi, you can get all the info in one query. But if you want to select only one row, you should use a WHERE clause telling what to look for.
Check this:
<?php
$servername = "localhost";
$username = "jon";
$password = "test";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
//test connection
if($conn -> connect_error) {
die("Connection Error: " . $conn -> connect_error);
}
//input from the user . addslashes is for security, so they won't break your query and potentially abuse it.
$firstname = addslashes($_POST['first']);
$lastname = addslashes($_POST['last']);
$email = addslashes($_POST['email']);
//query for the database to select the columns
$query = "SELECT firstname, lastname, email FROM users WHERE firstname = '$firstname' and lastname = '$lastname' and email = '$email'";
//query results
$result = $conn -> query($query);
$numRows = $result->num_rows;
//redirection if successful or if failure
$success = "../loggedin.php";
$failure = "../fail.php";
if($numRows > 0) {
header($success);
exit();
} else {
header($failure);
exit();
}
$conn -> close();
?>
Haven't tested it but the idea is to check for a match in the query, not afterwards. Then if there's a match, it will return at least one row (if you defined your table correctly it shouldn't be possible to have duplicates).
Then based on that you make your choice.

Get Specific Column data using mysqli_result()

I have a function which authenticates user for login.
$login_query = mysqli_query($GLOBALS['conn'],
"SELECT COUNT(`user_id`) as `count`,`user_id` FROM `users`
WHERE `user_email`='$email' AND `user_password` = '" . md5($password) . "'") or die(mysqli_error($GLOBALS['conn']));
return ($mysqli_result->num_rows == 1) ?
mysqli_result($login_query, 0, 'user_id') : false;
I was using mysql_* and now switching to mysqli_*.
What I want to know is that, in return statement how do I return user_id from the row that has been selected from DB?
I've simplified the query a little. This function will return the user_id if the login is successful or "0" if not.
Make the $mysqli connection in a config file that you can include at the top of each page
#config.php#
$dbhost = "localhost";
$dbuser = "";
$dbpassword = "";
$dbdatabase = "";
$salt = "";
$mysqli = mysqli_connect($dbhost,$dbuser,$dbpassword,$dbdatabase);
if (mysqli_connect_errno())
{
echo '<p>There was a problem with the mysqli connection:
<br> '.mysqli_connect_error().'</p>';
exit;
}
#Calling the function:#
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
checklogin($email, $password, $salt, $mysqli);
function checklogin($email, $password, $salt="", $mysqli)
{
$email = $mysqli->real_escape_string($email);
$password = $mysqli->real_escape_string($password);
$login_query = '
SELECT *
FROM
`users`
WHERE
`user_email`='$email'
AND
`user_password` = "' . md5($salt.$password) . '";';
$result = $mysqli->query($login_query)
$row = $result->fetch_array();
if ($result->num_rows > 0)
{$user_id = $row['user_id'];}
else
{$user_id = 0;}
return $user_ID
}

Categories