Prepared statements & select, 0 rows found - php

Alright so my problem is simple, Im trying to get results from a query but it always returns that there are no users registered with the username.
<?php
require "assembly/oop/sql_classbuild.php";
class player {
private $name;
private $age;
private $gender;
private $location;
public function createNew($name, $age, $gender, $location) {
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("INSERT INTO players (name, age, gender, location) VALUES (?,?,?,?)");
$stmt->bind_param("siss", $name, $age, $gender, $location);
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
$this->location = $location;
$stmt->execute();
$stmt->close();
$conn->close();
}
public function isRegistered($name) { //problematic code
$conni = new sql();
$conn = $conni->connect();
$stmt = $conn->prepare("SELECT name FROM players WHERE name=?");
$stmt->bind_param("s", $name);
$stmt->execute();
if($stmt->num_rows >= 1) { //if there is a registered member
$stmt->close();
$conn->close();
return true;
}
else {
$stmt->close();
$conn->close();
return false;
}
}
}
?>
Now I also tried to print num_rows but it just returns 0 as if there are no results inside the DB.
The usage is quite simple
if($player->isRegistered("Test") == true) {
echo "Hello";
}
else {
echo "Non-existing user";
}
SQL screenshot
http://imgur.com/a/TXqiJ
Also this is the sql class pastebin.com/Evg13CUc

The problem was resolved.
I used $stmt->store_result(); which somehow worked out and it gave me the good results.

Related

Insertion query get fired twice in php

I am trying to insert form data into MySQL using PHP but somehow the insert query get fired two times.I have attached my code below...please help if anyone know about solution...
<?php
class Product{
// database connection and table name
private $conn;
private $table_name = "lspl_user_profile";
// object properties
public $id;
public $fname;
public $lname;
public $job;
public $dept;
public $email;
public $password;
public function __construct($db){
$this->conn = $db;
}
public function create(){
try{
// insert query
$query = "INSERT INTO lspl_user_profile
SET fname=:fname, lname=:lname, job=:job, dept=:dept, email=:email, password=:password";
// prepare query for execution
$stmt = $this->conn->prepare($query);
// sanitize
$fname=htmlspecialchars(strip_tags($this->fname));
$lname=htmlspecialchars(strip_tags($this->lname));
$job=htmlspecialchars(strip_tags($this->job));
$dept=htmlspecialchars(strip_tags($this->dept));
$email=htmlspecialchars(strip_tags($this->email));
$password=htmlspecialchars(strip_tags($this->password));
// bind the parameters
$stmt->bindParam(':fname', $fname);
$stmt->bindParam(':lname', $lname);
$stmt->bindParam(':job', $job);
$stmt->bindParam(':dept', $dept);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
// Execute the query
if(empty($fname) ||empty($lname) || empty($job) ||empty($dept) ||empty($email) || empty($password) )
{
return false;
}
else
{
$stmt->execute();
mysqli_close($conn);
return true;
}
}
// show error if any
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
}
?>
This is create_product.php file...
<?php
if($_POST){
// include core configuration
include_once '../config/core.php';
// include database connection
include_once '../config/database.php';
// product object
include_once '../objects/product.php';
// class instance
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);
// set product property values
$product->fname = $_POST['fname'];
$product->lname = $_POST['lname'];
$product->job = $_POST['job'];
$product->dept = $_POST['dept'];
$product->email = $_POST['email'];
$product->password = $_POST['password'];
// create the product
echo $product->create() ? "true" : "false";
}
?>
This method send parameters to create_product.php
$.post("api/create_product.php", {
fname: this.state.fname,
lname: this.state.lname,
job: this.state.job,
dept: this.state.dept,
email: this.state.email,
password: this.state.password
}
);
Thank you, peoples..issue is resolved. Actually, I have made one silly mistake in HTML which causing post method invoke two time.
Especially, thanks to ADyson..

Fatal error: Call to undefined method mysqli_stmt::get_result() in demo.php on line 24

maybe this question is duplicate. but i cant find an answer for my problem.
i got this problem Fatal error: Call to undefined method mysqli_stmt::get_result() in demo.php on line 24
the line 24 is in this part of the code $tasks = $stmt->get_result();
here is my demo.php code.
<?php
/**
* Class to handle all db operations
* This class will have CRUD methods for database tables
*
* #author Ravi Tamada
* #link URL Tutorial link
*/
class Demo {
private $conn;
function __construct() {
require_once dirname(__FILE__) . '/include/db_connect.php';
// opening db connection
$db = new DbConnect();
$this->conn = $db->connect();
}
public function getAllChatRooms() {
$stmt = $this->conn->prepare("SELECT * FROM chat_rooms");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
public function getAllUsers() {
$stmt = $this->conn->prepare("SELECT * FROM users");
$stmt->execute();
$tasks = $stmt->get_result();
$stmt->close();
return $tasks;
}
public function getDemoUser() {
$name = 'AndroidHive';
$email = 'admin#androidhive.info';
$stmt = $this->conn->prepare("SELECT user_id from users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
if ($num_rows > 0) {
$stmt->bind_result($user_id);
$stmt->fetch();
return $user_id;
} else {
$stmt = $this->conn->prepare("INSERT INTO users(name, email) values(?, ?)");
$stmt->bind_param("ss", $name, $email);
$result = $stmt->execute();
$user_id = $stmt->insert_id;
$stmt->close();
return $user_id;
}
}
}
?>
in my index.php i have code to call the function.
this is the sample code
<?php
$chatrooms = $demo->getAllChatRooms();
foreach ($chatrooms as $key => $chatroom) {
$cls = $key == 0 ? 'selected' : '';
?>
<li id="<?= $chatroom['chat_room_id'] ?>" class="<?= $cls ?>">
<label><?= $chatroom['name'] ?></label>
<span>topic_<?= $chatroom['chat_room_id'] ?></span>
</li>
<?php
}
?>
please help me to construct this code.
thank you.
You need to install mysqlnd support. (MySQL Native Driver)
you can replace you function as bellow
i get problem like yours but this will solve please try it thank you
public function getAllChatRooms() {
$query = "SELECT chat_room_id, name, created_at FROM chat_rooms WHERE 1";
if ($result = mysqli_query($this->conn, $query)) {
return $result;
mysqli_free_result($result);
}
}
public function getAllUsers() {
$query = "SELECT user_id, name, email, gcm_registration_id, created_at FROM users WHERE 1";
if ($result = mysqli_query($this->conn, $query)) {
return $result;
mysqli_free_result($result);
}
}

Prepared query isn't working PHP

I'm trying to use prepared queries, but this code isn't working, it just stucks on the first use of prepare(). Commenting the fist if() does nothing, now it stucks on the second. No connection problems/no errors, just stuck.
If I do all of this using just mysqli_query() everything works great.
function addUser($id){
/*
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
if (!($stmt->bind_param("s", $id))){
return false;
}
if ($stmt->execute()) {
if ($stmt->num_rows!=0){
return false;
}
}else{
return false;
}
}else{
return false;
}*/
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
if (!$stmt->bind_param("s", $id)) {
return false;
}
if (!$stmt->execute()) {
return false;
}
return true;
}
return false;
}
and about debugging, if i change the code like this
function addUser($id){
echo "1";
if ($stmt = $this->mysqli->prepare("SELECT * FROM Users WHERE ID = ?")){
echo "2";
if (!($stmt->bind_param("s", $id))){
return false;
} ...
}else{
echo "3";
} ...
I'll see only "1" on the page.
start of the class:
class db{
private $mysqli;
function __construct($ip, $login, $password, $database){
$this->mysqli = new mysqli($ip, $login, $password, $database) or die("Problem with DB connection!");
$this->mysqli->set_charset("utf8");
}
You never execute() so nothing will happen, therefore no errors will raise.
Here is how I would write it:
function addUser($id){
if ($this->mysqli->connect_errno) {
die('Connect Error: ' . $this->mysqli->connect_errno);
}
if ($stmt = $this->mysqli->prepare("INSERT INTO Users VALUES (?, '')")) {
$stmt->bind_param("s", $id);//did you mean i for type int ?
$stmt->execute();//dont forget this!!
}else{
die('Connect Error: ' . $this->mysqli->connect_errno);
}
return ($stmt->rowCount() > 0)? true : false;
}

how to return a value from a method inside another method php

i got two methods.one method is to insert data and the other one is to get the id of the inserted data. i tried several test but it doesn't give any return value.is it possible to pass a return value from another method?
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
//$log = $this->getSessionID($email);
return $this->getSessionID($email);
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
public function getSessionID($email) {
try {
//global $bcrypt;
$query = $this->db->prepare("SELECT `id` FROM `registrants_info` WHERE `email` = ?");
$query->bindValue(1, $email);
$query->execute();
$data1 = $query->fetch();
$id = $data1['id'];
//echo $id;
return $id;
} catch(PDOException $e) {
die($e->getMessage());
}
}
and the returning page is here:
if($data = $admin->insertRegistrantInfo($fname, $lname) == true) {
session_regenerate_id(true);
$_SESSION['id'] = $data;
//print_r($_SESSION);
header('location: registry.php');
exit();
}
Use the lastInsertID() method on your query object rather than a second query
public function insertRegistrantInfo($fname, $lname) {
$query = $this->db->prepare("INSERT INTO `registrants_info` (`first_name`, `last_name`) VALUES (?,?)");
$query->bindValue(1, $fname);
$query->bindValue(2, $lname);
try {
$row = $query->execute();
$insertId = $query->lastInsertId(); // <!-- Use this instead of a second query
#mail function can be added here
}catch(PDOException $e) {
die($e->getMessage());
}
}
Its also important to note that you are not inserting the 'email address' into your database, so there is no way for the query to find it by that field if you were to use another SELECT statement. You might want to complete your INSERT statement.

INSERT query does not work, empty array?

<?php
class Worker extends Core {
public $name;
public $surname;
public $dob;
public $skills;
public $postcode;
public $street;
public $email;
public $tel;
public $ern;
public $result;
public function __construct () {
$this->name = 'name';
$this->surname = 'surname';
$this->dob = 'dob';
$this->skills = 'skills';
$this->postcode = 'postcode';
$this->street = 'street';
$this->email = 'email';
$this->tel = 'tel';
$this->ern = 'ern';
}
//Saving worker data to database, need provide group name (table name)
public function saveWorker($group) {
if(!(isset($this->conn))) parent::__construct();
try
{
$this->conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //catch exceptions
$q = 'INSERT INTO :group (name, surname, dob, skills, postcode, street, email, tel, erefnumber) VALUES (
:name,
:surname,
:dob,
:skills,
:postcode,
:street,
:email,
:tel,
:erefnumber)'; //sql query with group name
$stmt = $this->conn->prepare($q);
$stmt -> bindValue(':group', $group, PDO::PARAM_STR);
$stmt -> bindValue(':name', $this->name, PDO::PARAM_STR);
$stmt -> bindValue(':surname', $this->surname, PDO::PARAM_STR);
$stmt -> bindValue(':dob', $this->dob, PDO::PARAM_STR);
$stmt -> bindValue(':skills', $this->skills, PDO::PARAM_STR);
$stmt -> bindValue(':postcode', $this->postcode, PDO::PARAM_STR);
$stmt -> bindValue(':street', $this->street, PDO::PARAM_STR);
$stmt -> bindValue(':email', $this->email, PDO::PARAM_STR);
$stmt -> bindValue(':tel', $this->tel, PDO::PARAM_STR);
$stmt -> bindValue(':erefnumber', $this->erefnumber, PDO::PARAM_STR);
$results = $stmt->execute();
if($results > 0)
{
return 'Dodano: '.$ilosc.' rekordow';
}
else
{
return 'Wystapil blad podczas dodawania rekordow!';
}
}
catch(PDOException $e)
{
return 'There was some error: ' . $e->getMessage();
}
unset($stmt);
}
//no exceptions
public function getWorker()
{
$workerData = array (
"name" => $this->name,
"surname" => $this->surname,
"dob" => $this->dob,
"skills" => $this->skills,
"postcode" => $this->postcode,
"street" => $this->street,
"email" => $this->email,
"tel" => $this->tel,
"tel" => $this->erefnumber
);
return $workerData;
} // end getWorker();
public function searchWorker($name, $surname, $dob, $skills, $postcode, $street, $email, $tel, $erefnumber) {
}
function deleteWorker() {
}
function getEmployer() {}
public function __sleep () {
parent::__sleep();
}
} // end Person;
//DB connection
class Core {
public $conn;
public function __construct() {
$this->dbConnect();
}
public function dbConnect() {
$host = 'localhost';
$port = '3307';
$username = 'modium_test';
$password = 'test';
$database ='modium_test';
try{
$this->conn = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
echo 'Connection successful!';
echo var_dump($this->conn);
}
catch(PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
public function __sleep () {
unset($this->conn);
}
}
}
The query just doesn't work. Every previous function worked, but when I try to INSERT tables via sql query, nothing happends.
Worker is an object it's created well, then i get some POST array assigned to it, wich also works fine then i try to saveWorker but it gives nothing.
The invoking line:
var_dump($worker);
if (isset($worker)) echo 'worker is set';
if (isset($worker->conn)) echo 'thers connection is set';
$worker->saveWorker('workers');
With added lines:
echo "\nPDO::errorInfo():\n";
print_r($stmt->errorInfo());
print_r($this->conn->errorInfo());
echo "end of error info";
It gives me:
PDO::errorInfo():
Array ( [0] => ) Array ( [0] => 00000 )
end of error info
$stmt->execute() returns a boolean value (Manual). Try,
$results = $stmt->execute();
if($results !== FALSE) {
return 'Dodano: '.$ilosc.' rekordow';
} else {
return 'Wystapil blad podczas dodawania rekordow!';
}
Also, you cannot bind tablename.

Categories