Method in my class does it work properly. Don't give me some error message, but simply does not work.
public function query($value)
{
$this->__error = FALSE;
$sql = "SELECT * FROM users WHERE username = ".Input::input($value);
if ($this->__query = $this->__pdo->query($sql))
{
$this->__result = $this->__query->fetchAll(PDO::FETCH_OBJ);
$this->__count = $this->__query->rowCount(); //Here is the problem
}
else {
$this->__error = TRUE;
}
return $this;
}
public function count()
{
return $this->__count;
}
But I would not write whole class code, I mention that PDO DataBase connection is properly defined ($_pdo property), also the instance who is responsible to comunicate with database. ($_instance property). Input class too.
Here is my index.php (some kind of registration form):
<?php
spl_autoload_register(function($class) //Load all class in project
{
require_once 'class/'.$class.'.php';
}
);
$user = DataBase_class::instance()->query("username"); //username is the name of textbox
if ($user->count())
{
echo 'User exist';
}
else echo 'User not exist';
?>
Result is "User not exist", although user exist 100%.
You forget the quotes
$sql = "SELECT * FROM users WHERE username = '".Input::input($value) . "'";
but you should consider to use prepared statements..
$stmt = $this->__pdo->prepare("SELECT * FROM users WHERE username = :name");
$stmt->bindParam(':name', Input::input($value));
$result = $stmt->execute();
Related
What I want is to get and store the last inserted ID, but I am not sure how. The scenario is, after a user add a record he/she will be redirected to a page that will show him/her of the summary of what he/she saved. But I am not sure how I can do that, to retrieved the recently added record.
I have a class which look like this record.php
<?php
class Record {
private $conn;
private $table_name_1 = "name_of_the_table_1";
private $table_name_2 = "name_of_the_table_2";
public $name;
public $age;
public function __construct($db){
$this->conn = $db;
}
function newRecord(){
$query = "INSERT INTO " . $this->table_name_1 . " SET name=:name;
INSERT INTO " . $this->table_name_2 . " SET age=:age";
$stmt = $this->conn->prepare($query);
$this->name=$this->name;
$this->age=$this->age;
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':age', $this->age);
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
?>
now I have another php form that create and add record, the code is something like this add_record.php
<?php
inlude_once 'db.php'
inlude_once 'record.php'
$database = new Database();
$db = $database->getConnection();
$record = new Record($db);
?>
<?php
if($_POST) {
$record->name=$_POST['name'];
$record->age=$_POST['age'];
if(record->record()){
header("Location:{$home_url}view_recently_added_record.php?action=record_saved");
}
else{
echo "Unable to save";
}
}
?>
The idea is to save the query to two different table and the same time automatically record the auto increment ID of table 1 to table 2 so that they have a relationship. I am thinking I can do that if I can store immediately the ID from table 1 and assigned it a variable maybe so it can be automatically saved to table two using a new query or function maybe. Is this possible? does it make sense? and another thing I wanted to display the recently recorded data immediately to the user. Thank you.
You can return $stmt->insert_id or -1 insteaf of boolean in the newRecord function:
function newRecord(){
...
if($stmt->execute()){
return $stmt->insert_id;
}else{
return -1;
}
}
and use the value to redirect like this:
$newrecord = record->newRecord();
if($newrecord != -1) {
header("Location:{$home_url}view_recently_added_record.php?action=record_saved&id=".$newrecord);
}
else{
echo "Unable to save";
}
I Have a Problem With Source Code PHP PDO . I Try make a CRUD with PHP PDO , but when i try source code for delete and when I run a script the Data do not want to be erased .. I apologize if my speaking was nothing wrong, I am from Indonesian
Thank's Before
Script function delete :
public function deleteData($id)
{
// fungsi menghapus data dari database
$this->id = $id;
$this->sql = "DELETE FROM student WHERE id=:id";
$this->q = $this->dbh->prepare($sql);
$this->q->bindParam(":id",$this->id);
$this->q->execute();
return true;
}
Script delete.php
<?php
include "belajar_crud.php";
$obj = new crud;
$id = isset($_GET['id']) ? $_GET['id']:'';
$obj->deleteData($id);
?>
Change this line:
$this->q = $this->dbh->prepare($sql);
Into this:
$this->q = $this->dbh->prepare($this->sql);
This is the only error I see in the code...
If this is not the case, you need to provide more information.
why you no try this?
config.php:
define('HOST','your host');
define('BD','your database');
define('USER','your user');
define('PASS','your password');
BD.class.php:
class BD{
private static $conn;
public function __construct(){}
public function conn(){
if(is_null(self::$conn)){
self::$conn = new PDO('mysql:host='.HOST.';dbname='.BD.'',''.USER.'',''.PASS.'');
}
return self::$conn;
}
}
your code of delete:
#BD::conn();
$query = #BD::conn()->prepare("DELETE FROM YOURTABLE WHERE ID = ?");
if($query->execute(array($this->id))){
echo "<script>alert('Delete Successful');</script>";
}
Below is some code that works fine, however it used mysql_* and i dont want that anymore. I have tried to redo this section in mysqli but it's not working. I can post my entire code if you wish, but i am certain i know where the issue lies. Below is the code:
Old:
public function verifyDatabase()
{
include('dbConfig.php');
$data = mysql_query("SELECT client_id FROM clients WHERE client_email_address = '{$this->_username}' AND client_password = '{$this->_pass_sha1}'");
if(mysql_num_rows($data))
{
list($this->_id) = #array_values(mysql_fetch_assoc($data));
return true;
}
else
{
return false;
}
}
New:
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows)
{
list($this->_id) = #array_values($data->fetch());
return true;
}
else
{
return false;
}
}
I'm still learning mysqli and not quite ready for PDO stuff as i found that a little confusing. As i say, this whole script works perfectly with mysql_* but not so much with mysqli. When i try and log in my form doesnt display any errors nor does it push forward to the next page, so i know its this bit that is the issue
it is advised to use a helper function, either with old mysql or modern mysqli
public function verifyDatabase()
{
$sql = "SELECT client_id FROM clients WHERE email = ? AND password = ?";
return $this->db->getOne($sql ,$this->_username,$this->_pass_sha1);
}
Also note that dbConfig.php should not be included in the every method but, but only once. While DB handler should be assigned to a class variable in the constructor.
Change your code to this. I'm not saying it will fix problems but will be better.
public function verifyDatabase()
{
include('dbConfig.php');
$data = $db->prepare("SELECT client_id FROM clients WHERE client_email_address = ? AND client_password = ? LIMIT 1");
$data->bind_param($this->_username, $this->_pass_sha1);
$data->execute();
$data->store_result();
if($data->num_rows > 0)
{
$result = $data->fetch();
$this->_id = $result['client_id'];
return true;
}
else
{
return false;
}
}
You can also put var_dump($result); after the $result = $data->fetch(); line to print out what exactly is being returned.
class Application_Model_DbTable_Email extends Zend_Db_Table_Abstract
{
protected $_name = 'memberdetail';
function getUserid($email)
{
$subquery = $this->select()
->from('memberdetail', array('memberid'))
->where('email = ?', $email);
$select = $this->select()
->from('usertable', array('userid'))
->join('memberdetail', 'usertable.userid = memberdetail.memberid')
->where('usertable.userid = ?', $subquery);
$row = $select->query()->fetch();
if (!$row) {
echo "User id not found";
} else {
return $userid = $row['userid'];
}
}
}
Hi, I am trying to return the userid from the above queries. However, the queries does not seemed to be executed as I always get refreshed whenever I call this function.
P.S this set of queries were given to me by another member.
it looks like this is being over thought. According to the info provided usertable.userid = memberdetail.memberid with this being the case your function is simple.
/** this function assumes one and only one email will match a memberid
* this function can be improved by validating $email as existing in DB
* prior to querying DB, should be done at form level but could be accomplished here
* with Zend_Validate_Db_RecordExists()
*/
public function getUserIdFromEmail($email) {
$select = $this->select();
$select->where('email = ?',$email);
$row = $this->fetchRow($select);//fetch a single row
if (!is_null($row) {//fetchRow returns null if no row matched
return $row->memeberid;//return memberid as string/integer = usertable.userid
} else {
//handle error
}
}
It would have been useful to tell people you are using Zend framework.
You need to establish a connection to the database for $this as described in steps 1 and 2 in this link:
http://framework.zend.com/manual/en/zend.db.select.html/
You can try this, if it helps:
function getUserid($email){
$select = $this->select()
->setIntegrityCheck(false)
->from(array('m' => 'memberdetail'), array('b.userid'))
->join(array('b' => 'usertable'), 'b.userid = m.memberid')
->where('m.email = ?', $email);
$row = $this->getAdapter()->fetchAll($select);
if (!$row) {
throw new Exception("User id not found");
} else {
return $row->toArray();
}
}
If I declare a global variable such as a database connection of $mysqli how do I use that in a class. i am trying to use it in my user class. Do i store it as a public variable in the class or as a global in the function itself. I also think there is something wrong with my following code but I may be wrong.
class USER
{
function __constructor()
{
}
/*
* adds a new user
* returns FALSE on error
* returns user id on success
*/
function add_member($name, $email, $password)
{
global $mysqli;
$query = "INSERT INTO members
SET
user_name = {'$name'},
user_email = {'$email'},
password = ['$password'}";
$success = $mysqli -> query ($query);
if (!$success || $mysqli -> affected_rows == 0)
{
echo "<p> An error occurred: you just are not tough enough!!!</p>";
return FALSE;
}
$uid = $mysqli -> insert_id;
return $uid;
}
} // end class
$uc = new USER();
?>
<?php
require_once ('includes/classes/database.php');
require_once('includes/classes/user.php');
require_once('includes/header.php');
// if user submits a new registration
if (isset($_POST['name'],$_POST['email'],$_POST['pwd'],$_POST['pwd2']))
{
// validate input fields
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['pwd'];
$password2 = $_POST['pwd2'];
// if error fall through and redisplay page with errors
// if no errors update database and redirect to homepage
if ($uc->add_member($name, $email, $password) === FALSE)
{
echo "System Error. damn if I know what to do";
}
else
{
header("location: homepage.php");
}
}
You um... don't. Instead use a variable inside of the class:
class USER
{
private $mysql;
function __constructor($mysqli)
{
$this->mysqli = $mysqli;
}
function add_member($name, $email, $password)
{
$mysqli = $this->mysqli;
/* yada yada */
Couple of issues by the way:
// You want the ' outside of the {}
$query = "INSERT INTO members
SET
user_name = '{$name}',
user_email = '{$email}',
password = '{$password}'";// there was a [ not a {
You also want to call mysqli_real_escape_string on all of those variables. Or better yet use mysqli_bind_param and a prepared statement.