mysql queries does not work in zend framework - php

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();
}
}

Related

Cannot get data from mysql query to controller

Hello I am using codeigniter framework for a project, I have a controller which is calling the data from a model function. Here is the controller.
public function getThirdPartyRR($token){
if ($this->input->is_ajax_request()){
// $data = json_decode(file_get_contents('php://input'), true);
// Following is loaded automatically in the constructor.
//$this->load->model('user_profile');
$userid = $this->myajax->getUserByAuth($token);
if ($userid){
$this->load->model("riskrating_page");
/* If we have an impersonated user in the session, let's use him/her. */
if (isset($_SESSION['userImpersonated'])) {
if ($_SESSION['userImpersonated'] > 0) {
$userid = $_SESSION['userImpersonated'];
}
}
// $resultList value could be null also.
$result = $this->riskrating_page->getThirdPartydata($userid);
/* Little bit of magic :). */
$thirdpartylist = json_decode(json_encode($result), true);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($thirdpartylist));
} else {
return $this->output->set_status_header('401', 'Could not identify the user!');
}
} else {
return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
}
}
And here is the query function in the model where I get the data from.
function getThirdPartydata($id){
$query = 'SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = \'user_thirdparty_rr\'
WHERE a.Owner = '.$id. ' and
a.UPDATE_DT is null;';
}
But when I debug it using netbeans, its shows that in my controller in the $result function I get null meaning I couldnt grab any data from mysql.
Here is the search result from mysql.
You only write your query not fetch any data from your query result
function getThirdPartydata($id){
$query = "SELECT b.text_value as Company, a.third_party_rr_value
FROM user_thirdparty_rr a
inner join text_param_values b
on a.third_party_rr_type = b.text_code and
b.for_object = 'user_thirdparty_rr'
WHERE a.Owner = '$id' and
a.UPDATE_DT is null";
$this->db->query($query);// execute your query
return $query->result_array();// fetch data
}

Catching the returned value

this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.

PDO:: What's wrong with this query?

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();

Switching from mysql to mysqli issues

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.

PHP PDO and DELETE with in() not working

Here is the code for the class:
class Delete_Category extends Category {
private $idchain = array();
public function __construct($id) {
parent::__construct();
$this->check_id($id);
$this->get_delete_ids($this->id);
$this->delete_category($this->idchain);
}
// Get all the Children IDs from the DB and store them in the array
private function get_delete_ids($id) {
$this->query = $this->db->prepare("SELECT id FROM `shop_categories` WHERE parent_id = :id");
$this->query->execute(array("id" => $id));
while($result = $this->query->fetch(PDO::FETCH_ASSOC)) {
$this->get_delete_ids($result['id']);
}
$this->idchain[]= $id;
}
// Implode the array into an id string and throw it in the query
private function delete_category($id_array) {
$id = implode(",",$id_array);
try {
$this->query = $this->db->prepare("DELETE FROM `shop_categories` WHERE id IN (:id)");
$this->query->execute(array(':id' => $id));
}
catch(PDOException $e) {
// log it{
}
}
}
The thing is that this always ends up with only the last ID being deleted. The query seems to be working however because it looks totaly fine if i echo it and replace :id with $id.
// SQL output string if echoed:
DELETE FROM `shop_categories` WHERE id IN (11,6)
// If i manually add this to the Database it works as intended so the problem has to be somewhere at the PDO statement... Can anyone help me?
You can use FIND_IN_SET for that:
DELETE FROM `shop_categories` WHERE FIND_IN_SET(id, :id)"

Categories