i have this script to connect my DB and i get error 500 when using it.
I tried to track where the error is and i think its at this line: while ($row = $stmt->fetch_assoc())
But i looked over examples and its the same is mine.
Here is my code thanks for helping:
<?php
$mysqli = new mysqli(*MY DB DETAILS*);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM comments WHERE workout_name =? AND user =?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$workout_name = $_GET['workout_name'];
$user = $_GET['user'];
$stmt->execute();
if ($stmt)
{
while ($row = $stmt->fetch_assoc())
{
$response["name"] = $row["workout_name"];
echo json_encode($response);
}
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
$response["success"] = 2;
// echoing JSON response
echo json_encode($response);
}
?>
UPDATE:
I had to change $row = $stmt->fetch_assoc()
as described here:
How to remove the fatal error when fetching an assoc array
Before you do this line
$stmt->bind_param('ss', $workout_name, $user);
You have to set $workout_name and $user to contain a value.
eg
$workout_name = 'pumping iron';
$user = 'Arnold Schwarzenegger';
$stmt->bind_param('ss', $workout_name, $user);
In your case as you have not even created these variables yet. I assume you are getting the 500 error because the mysqli code goes BANG trying to find NON-EXISTANT variables to load data from.
Related
This question already has answers here:
mysqli query results to show all rows
(4 answers)
Closed 6 years ago.
I am trying for getting multiple records from database but when I try for more then one records. I always getting empty.
First I try FROM DbOperation.php:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT DateString FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
php data get
<?php
require_once 'DbOperation.php';
$db = new DbOperation();
$DateString = $_POST['DateString'];
$devices = $db->getDayListByDate($DateString);
$response = array();
$response['error'] = false;
$response['devices'] = array();
while($device = $devices->fetch_assoc()){
$temp = array();
$temp['Question']=$device['Question'];
$temp['Option_2']=$device['DateString'];
array_push($response['devices'],$temp);
}
echo json_encode($response);
Response: {"error":false,"devices":[{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"},{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}{"Question":null,"Option_2":"10/1/2016 12:00:00 AM"}]}
But when I trying for all records and change database query for getting Question field in reponse like.
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= ?");
$stmt->bind_param("s",$DateString);
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
I am getting result empty like "".
I am using for connection
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Config.php';
//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//finally returning the connection link
return $this->con;
}
I think the way you are binding is incorrect too:
public function getDayListByDate($DateString){
$stmt = $this->con->prepare("SELECT * FROM gk_eng WHERE DateString= :DS");
$stmt->bind_param(":DS",$DateString);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
Try This
function getDayListByDate($DateString) {
$result = $this->con->query("SELECT * FROM gk_eng WHERE DateString='$DateString' ");
return $result;
}
you can get answer.. if didnt get ans .. let me know
I have a PDO that is querying a non-existant user in the database to handle user registration. The problem is, var_dump and print_r both do not print anything if the user is not found.
try {
$stmt->execute();
while($row = $stmt->fetch()) {
var_dump($row);
print_r($row);
if($row = null) { // Not working
# if(!isset($row)) { // Not working
# if(empty($row)) { // Also not working
echo "User not found";
} else {
echo $row['realname']."<br>";
}
}
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
What is happening here? The page is just blank.
php -l index.php repors no syntax errors and the page is not throwing error 500.
Nothing in view source either.
Here is connection details:
try {
$dbh = new PDO('mysql:host=127.0.0.1;dbname=PHP_PDO', "root", "root", array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
} catch(PDOException $e) {
die("FATAL ERROR OCCURED");
}
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATA BASE
The reason why it's not working, is that you are "assigning" in if($row = null) using 1 equal sign, rather than "comparing" if($row == null) with 2 equal signs (or 3 "if identical", depending on what you want to check for).
Consult: The 3 different equals here on Stack about this.
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
PHP sees the "assignment" as being valid syntax and that is why you are not receiving any errors.
Turns out i had to reorganize the code a bit.
I took the $row = $stmt->fetch(); out of the while loop, and checked the $row seperately. Like this:
$stmt = $dbh->prepare("SELECT realname FROM users WHERE name = :name" );
$stmt->bindParam(":name", $name);
$name = "mivuckovaca"; // NOT IN DATABSE ON PURPOSE
try {
$stmt->execute();
} catch(PDOException $e) {
echo "FATAL ERROR OCCURED:".$e->getMessage();
}
$res = $stmt->fetchAll(); # Replaced fetch() with fetchAll()
if(empty($res)) {
echo "User not found";
} else {
foreach($res as $row) { # replaced while() with foreach()
echo $row['realname'];
}
}
im trying to get some data from my DB using this code:
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$mysqli2 = new mysqli(********************);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql2 = "SELECT message FROM wall_workouts_names WHERE id = ? ";
$stmt2 = $mysqli2->prepare($sql2) or trigger_error($mysqli2->error."[$sql2]");
$id_for_wall = '43';
$stmt2->bind_param('s', $id_for_wall);
$stmt2->execute();
$stmt2->bind_result($message);
$stmt2->store_result();
$stmt2->fetch();
echo $message;
?>
My problem is that i get empty string in my echo.
But if i run the same query in my phpmyadmin i get good results.
Thanks for helping
Most likely there are no row to match condition in your WHERE clause, namely with id = 43
Check your incoming results like this.
while ($stmt->fetch()) {
echo $message;
}
I'm creating an authentification file with php and mysql, but I have this mistake in this line:
$stmt2->bind_param('ss',$twitter_id, $name);
The error message is
Call to a member function bind_param() on a non-object in ...
Where's my mistake?
$name in my database is a VARCHAR
$twitter_id in my database is a VARCHAR
$bd is my database connection
If a user is already registered, it should show me a message saying "User already registered", and if the user isn't registered, it should insert a new id and name in my database.
session_start();
if (!isset($_SESSION['userdata'])) {
header("location: index.php");
} else {
$userdata = $_SESSION['userdata'];
$name = $userdata->name;
$twitter_id = $userdata->id;
$stmt = $bd->prepare("SELECT ID_TWITTER FROM USERS");
$stmt->execute();
$stmt->bind_result($checkUser);
if ($stmt->fetch()) {
if($checkUser!==$twitter_id){
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME) VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss',$twitter_id, $name);
$stmt2->execute();
$stmt2->close();
} else {
echo "User already exits";
}
}
$stmt->close();
}
Could it be a typo? does $bd exist or should it be $db ?
Shameless plug: I do this exact thing in a project I have on github. Feel free to use the classes for whatever you like; they are mostly copy-pastable.
Your real issue is that $bd->prepare() returned false.
Check that you actually called it correctly and set it to new mysqli(*params)
The error Call to a member function ... on a non-object in ... means that $db is not an object, which means that it was not instantiated to an object. Thus, $this->method() isn't possible. bind_param(string $format, mixed &*vars); uses pass-by-reference and if this fails, it throws an error.
Try it yourself by sticking this in there:
$stmt->bind_param("ss", "string", "string");
To get around this issue where it can fail, check if $db->prepare() returns true:
if ($query = $bd->prepare($sql)) {
//stuff
}
In addition, in the first query you do it is probably not a good idea to be adding the overhead of a prepare for a single query that only checks row count without user input.
Solved : it works now
$stmt = $bd->prepare("SELECT ID_PROVIDER FROM USERS WHERE ID_PROVIDER = ?");
$stmt->bind_param('s', $twitter_id);
$stmt->execute();
$stmt->bind_result($checkUser);
while ($stmt->fetch()) {
$result = $checkUser;
}
if (empty($result)) {
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME)
VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss', $twitter_id, $name);
$stmt2->execute();
$stmt2->close();
}else {
echo "User already exits";
}
If i've database table with users(name,job) (john,Poster) and i made query with MySQLi using this code and that would works.
$job = "Poster";
$statement = $con->prepare("SELECT * FROM users WHERE `job` = ?");
$statement->bind_param("s",$job);
$statement->execute();
$statement->bind_result($name,$job);
while ($statement->fetch()){
echo $name;
}
what if i made $job = "NOTHING"; and there was no results then how can i show error such as echo "No reuslts found"; !! the above code if $job was not found it will show nothing. ~ thanks
EDIT
this one didn't worked too :(
$job = "NOTHING"; // should not found and should gives error
if ($statement = $con->prepare("SELECT * FROM users WHERE `job` = ?")){
$statement->bind_param("s",$job);
$statement->execute();
$statement->bind_result($name,$job);
while ($statement->fetch()){
echo $name;
}
}else{
echo "No results found dude";
}
Do not use mysqli. It is unusable with prepared statements.
Use PDO instead.
With PDO your code would be shorter, sensible and works.
$statement = $con->prepare("SELECT * FROM users WHERE `job` = ?");
$statement->execute(array($job));
if ($row = $statement->fetch()){
echo $row['name'];
} else {
echo "No results found dude";
}
You need to create a connection first. Something like this
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'dbuser';
$pass = 'dbpass';
$con = new PDO($dsn, $user, $pass);
You can see details on the manual page
As a further step you can move to some helper library, which will make your code even shorter:
$name = $db->getOne("SELECT name FROM users WHERE job=?s",$job);
if ($name) {
echo $name;
} else {
echo "No results found dude";
}
But it would be wise to get yourself familiar with raw API functions first.