PDO execute problem - php

I have faced a problem .I want to select all rows by executing this function:
public function executeQuery($query,$fetch_mode=null) {
$rs = null;
if ($stmt = $this->getConnection()->prepare($query)) {
if ($this->executePreparedStatement($stmt, $rs,$fetch_mode)) {
return $rs;
}
} else {
throw new DBError($this->getConnection()->errorInfo());
}
}
private function executePreparedStatement($stmt, & $row = null,$fetch_mode=null) {
$boReturn = false;
if($fetch_mode==null) $fetch_mode=$this->fetch_mode;
if ($stmt->execute()) {
if ($row = $stmt->fetch($fetch_mode)) {
$boReturn = true;
} else {
$boReturn = false;
}
} else {
$boReturn = false;
}
return $boReturn;
}
But when I call it from my index page:
$objDB=new DB();
$objDB->connect();
// executeQuery returns an array
$result=$objDB->executeQuery("SELECT * FROM admin");
var_dump($result);
Only a single row is retrieved instead of all rows.
I also set mode using:
$result=$objDB->executeQuery("SELECT * FROM admin",PDO::FETCH_ASSOC);
But it still does not work.

The fetch method returns only the current row and sets the row pointer to the next row. To read all data in a PHP array you can use fetchAll().
Additionally return-by-reference is no good idea in PHP as it messes with PHP's copy-on-write mechanism and often creates trouble.
So I'd write oyure code something like this:
public function executeQuery($query,$fetch_mode=null) {
if ($stmt = $this->getConnection()->prepare($query)) {
$ret = $this->executePreparedStatement($stmt, $fetch_mode);
return $ret;
}
throw new DBError($this->getConnection()->errorInfo());
}
private function executePreparedStatement($stmt, $fetch_mode=null) {
if($fetch_mode==null) $fetch_mode=$this->fetch_mode;
if ($stmt->execute()) {
if ($rows = $stmt->fetchAll($fetch_mode)) {
return $rows;
}
}
return false;
}

Related

Check Function without execute it

i'm training SOLID/Architectures and trying to make an INSERT on my code, but its insert four times on DB. There's any error on my logic? I'm following Repositories/Service Pattern.
i think my service is executing two times, but i cant find the reason.
Repositorie Code
public function inserirEstoque($dadosPost)
{
if (empty($dadosPost)) {
return false;
}
$pdo = $this->dbConnection->conectar();
$sql = $pdo->prepare('INSERT INTO estoque (nomeProduto, descriptions, price, quantity)
VALUES (:nome, :descriptions, :price, :quantity)');
$sql->bindValue(':nome', $dadosPost['nomeProduto']);
$sql->bindValue(':descriptions', $dadosPost['descriptions']);
$sql->bindValue(':price', $dadosPost['price']);
$sql->bindValue(':quantity', $dadosPost['quantity']);
$res = $sql->execute();
if($res == false)
{
return false;
}
return $res;
}
Service
public function insertEstoque()
{
$db = new MySQL();
$insert = new EstoqueRepositories($db);
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
}
Controller
public function insert()
{
$insert = new EstoqueService();
$insert->insertEstoque();
header('Location: ../../index.php');
}
It's executing twice because of this
if(!empty($insert->inserirEstoque($_POST))){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
if you wanna check if the POST data is empty just remove where it inserts the data then it should just insert it 1 time
if(!empty($_POST["whatevername"])){
return $insert->inserirEstoque($_POST);
} else {
return false;
}
As an addition to Reed's answer, if you just want to check the result of a function call before carrying on, assign the result to a variable and use that variable.
$res = $insert->inserirEstoque($_POST)
if(!empty($res)){
return $res;
} else {
return false;
}

Codeigniter not getting data though available in mysql database

I have a model which fetch the data from database is below
public function counselor() {
$inst_id = $this->session->userdata('user_id');
$submission_key=$this->session->userdata('submission_key');
$query = $this->db->query("SELECT * FROM counselor where USER_ID = $inst_id AND submission_key= $submission_key");
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}
}
I have tested the $inst_id and $submission_key by printing it and its set.
$inst_id=2 and $submission_key=2016-8 .BUT though I have one record in database with those two field set its not returning the data. What is the case. I have tried with codeigniter get() and where() method too. Still not giving me the result.
Just write your query using active record function. It will help you in escaping string
$this->db->select('*',FALSE);
$this->db->where('USER_ID',$inst_id);
$this->db->where('submission_key',$submission_key);
$query=$this->db->get('counselor');
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}

set was executed successfully in redis but get nothing

I'm using phpredis in my program, store something in the redis server, get them when the same request comes(in the same day), but I always get empty result. Can anyone give me some enlightenment? Here is the code of Cache class I'm using:
<?php
class Cache
{
public static function getInstance()
{
static $instance = null;
null == $instance && $instance = new self();
return $instance;
}
protected function __construct()
{
}
protected function getR()
{
static $r = NULL;
if (NULL == $r) {
$r = new Redis();
try {
$r->pconnect(HOST, PORT, 5);
} catch(Exception $ex) {
//log
try {
$api->connect(HOST, PORT, 5);
} catch (Exception $ex) {
//log
}
}
}
return $r;
}
public function getValue($key)
{
$result = array();
$r = $this->getR();
if(!empty($r)) {
try{
$result = $r->hKeys($key);
$r->setTimeout($keys, 86400);
} catch (Exception $ex){
//log
}
}
return $result; // return true
}
public function setValue($key, $value)
{
$result = false;
$r = $this->getR();
if(!empty($r)) {
try{
$result = $r->hMset($key, $value);
} catch (Exception $ex){
//log
}
}
}
}
?>
EDIT:
I checked the key-values with redis-cli, found something wired: the key-value data was stored in db 5 while I thought it should be in DB 0 by default without select statement, but the program retrieved db 0, of course nothing returned. Now I'm wondering why the data went to DB 5 given that I've not selected DB.
Finally, I've figured out what happend here. Before I stored my key–value pair, there was some code which also had communicated with Redis server and it had explicitly selected the DB 5, and the default DB of my redis connection was affected by last context, so my data was stored in DB 5. By coincidence, when I wanted to retrive my data, the last redis connection used DB 0, of course I got nothing.

PHP: fatal error: call to a member function get() on non object

I got an error while running my code, it says call to a member function getBallparkDetailsStartDate() on a non-object.
if($projectStatusId == ProjectStatusKeys::BALLPARK_ACTIVE) {
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
$projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
$projectDetails["enddate"] = $ballpark->getBallparkDetailsEndDate();
$projectDetails["projectid"] = $projectId;
$projectDetails["name"] = $ballpark->getBallparkDetailsBookingRef();
$projectDetails["status"] = ProjectStatusKeys::BALLPARK_ACTIVE;
}
I got the error in this line: $projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
Here is my other code:
public function __construct($ballparkDetailsId, $project,
$ballparkDetailsBookingRef,
$ballparkDetailsStartDate, $ballparkDetailsEndDate,
$ballparkDetailsExpiryDate, $ballparkDetailsDescription,
$ballparkDetailsNotes) {
$this->ballparkDetailsId = $ballparkDetailsId;
$this->project = $project;
$this->ballparkDetailsBookingRef = $ballparkDetailsBookingRef;
$this->ballparkDetailsStartDate = $ballparkDetailsStartDate;
$this->ballparkDetailsEndDate = $ballparkDetailsEndDate;
$this->ballparkDetailsExpiryDate = $ballparkDetailsExpiryDate;
$this->ballparkDetailsDescription = $ballparkDetailsDescription;
$this->ballparkDetailsNotes = $ballparkDetailsNotes;
}
public function getBallparkDetailsId() {
return $this->ballparkDetailsId;
}
public function getProject() {
return $this->project;
}
public function getBankName() {
return $this->getProject()->getBankName();
}
public function getBankRef() {
return $this->getProject()->getBankRef();
}
public function getRegionName() {
return $this->getProject()->getRegionName();
}
public function getProjectStatusName() {
return $this->getProject()->getProjectStatusName();
}
public function getBallparkDetailsBookingRef() {
return $this->ballparkDetailsBookingRef;
}
public function getBallparkDetailsStartDate() {
return $this->ballparkDetailsStartDate;
}
public function getBallparkDetailsEndDate() {
return $this->ballparkDetailsEndDate;
}
public function getBallparkDetailsExpiryDate() {
return $this->ballparkDetailsExpiryDate;
}
public function getBallparkDetailsDescription() {
return $this->ballparkDetailsDescription;
}
public function getBallparkDetailsNotes() {
return $this->ballparkDetailsNotes;
}
public function getProjectId() {
return $this->getProject()->getProjectId();
}
public function getProjectStatusId() {
return $this->getProject()->getProjectStatusId();
}
}
?>
The last time I check this it ran well. But now I don't know what's wrong with this? Please help me find the error. Thanks.
Apparently
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
is not returning a "ballpark" at all. Probably it is returning an error, or something like an empty array.
Try var_dump()'ing $ballpark immediately before the line that raises the error, and see what it contains (probably False, NULL, array() or something equally un-ballparky.
Then, inspect the ballparkDetailsByProjectId() function in the BallparkDetailsHandler.php file. At a guess, you might be passing an invalid (i.e. nonexistent, removed, etc.) $projectId.
Then you might rewrite the code with error checking:
if($projectStatusId == ProjectStatusKeys::BALLPARK_ACTIVE) {
$ballpark = $this->ballparkDetailsHandler->getBallparkDetailsByProjectId($projectId);
if (!is_object($ballpark))
trigger_error("Error: bad project ID: '$projectId': $ballpark",
E_USER_ERROR);
$projectDetails["startdate"] = $ballpark->getBallparkDetailsStartDate();
$projectDetails["enddate"] = $ballpark->getBallparkDetailsEndDate();
$projectDetails["projectid"] = $projectId;
$projectDetails["name"] = $ballpark->getBallparkDetailsBookingRef();
$projectDetails["status"] = ProjectStatusKeys::BALLPARK_ACTIVE;
}
Then in the BallparkDetailsHandler.php file you could modify this code:
// Prepare query or die
if (!($stmt = $this->mysqli->prepare($query))
return "Error in PREPARE: $query";
$stmt->bind_param("i", $projectId);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ballparkDetailsBookingRef, $bankRef, $regionName,
$projectStatusId, $projectStatusName, $ballparkDetailsDescription,
$ballparkDetailsNotes, $ballparkDetailsStartDate, $ballparkDetailsEndDate,
$ballparkDetailsExpiryDate);
$stmt->fetch();
// If no data, then die
if(!$stmt->num_rows)
return "No data in DB for projectID '$projectId': $query";
// Should be clear sailing from here on. Actually I ought to check
// whether all these new() here do return anything sensible, or not
$bank = new Bank("", "", $bankRef, "");
$region = new Region("", $regionName, "");
$projectStatus = new ProjectStatus($projectStatusId, $projectStatusName);
$project = new Project($projectId, $bank, $region, $projectStatus);
return new BallparkDetails("", $project,
$ballparkDetailsBookingRef, $ballparkDetailsStartDate,
$ballparkDetailsEndDate, $ballparkDetailsExpiryDate,
$ballparkDetailsDescription, $ballparkDetailsNotes);
$ballpark clearly doesn't contain the object you think it does on the line with the error. In fact, it obviously doesn't contain an object at all.
This implies that the preceding line (which sets $ballpark) isn't working properly. It would appear that it's returning a value that is is not an object.
I can't tell what that value is -- it could be null, or it could be an integer, string, array, etc. But whatever it is, it isn't a ballpark object.
I suggest you look at your getBallparkDetailsByProjectId() method to find the source of this problem.

Working with multiple objects of the same type (PHP)

What is the corecte way to handle with al lot objects of the same type?
Example:
When i get a list of notes from the database with zend framework i get a rowset which contains an array with note data.
If the number of notes in the database is 20 records large it's no problem to create a note object for every note in the database. But if the database contains 12.500 note records what shall i do than? Try to create 12.500 objects is possible but it's shure isn't quick enough.
Ty, Mark
This is the code i use.
Code to get the data from the database:
if (is_numeric($id) && $id > 0) {
$select = $this->getDao()->select();
$select->where('methode_id = ?', $id);
$select->order('datum DESC');
$rowset = $this->getDao()->fetchAll($select);
if (null != $rowset) {
$result = $this->createObjectArray($rowset);
}
}
createObjectArray function:
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
foreach ($rowset as $row) {
$model = new Notes();
$this->populate($row, $model);
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}
}//endforeach;
return $result;
}
Populate function
private function populate($row, $model)
{
// zet de purifier uit om overhead te voorkomen
if (isset($row['id'])) {
$model->setId($row['id']);
}
if (isset($row['type'])) {
$model->setType($row['type']);
}
if (isset($row['tekst'])) {
$model->setLog($row['tekst']);
}
if (isset($row['methode_id'])) {
$model->setSurveyMethodId($row['methode_id']);
}
if (isset($row['klant_id'])) {
$model->setCustomerId($row['klant_id']);
}
if (isset($row['gebruiker_aangemaakt_tekst'])) {
$model->setCreatedByUser($row['gebruiker_aangemaakt_tekst']);
}
if (isset($row['gebruiker_gewijzigd_tekst'])) {
$model->setUpdatedByUser($row['gebruiker_gewijzigd_tekst']);
}
if (isset($row['gebruiker_aangemaakt'])) {
$model->setCreatedByUserId($row['gebruiker_aangemaakt']);
}
if (isset($row['gebruiker_gewijzigd'])) {
$model->setUpdatedByUserId($row['gebruiker_gewijzigd']);
}
if (isset($row['datum_aangemaakt'])) {
$model->setDateCreated($row['datum_aangemaakt']);
}
if (isset($row['datum_gewijzigd'])) {
$model->setDateUpdated($row['datum_gewijzigd']);
}
$model->clearMapper();
return $model;
}
You could page your requests, so you only get a set amount of notes back each time. Although I can't see a problem with "only 12,500" objects, unless your object creation is doing something costly, i.e more queries on the database etc.
I am not so sure about your question.
For eg :
//Create a single object
$obj = new NoteObject();
//Set the properties if it differs
$obj->setX( $row );
//Make use of the method
$obj->processMethod();
So this way you just need a single object. Lets see the code if its not to give you a right answer.
Edit :
What I thought was in
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
//Create the model here
$model = new Notes();
foreach ($rowset as $row) {
//Yes populate the values
$this->populate($row, $model);
/*
And not like saving the object here in array
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}*/
//Do some calculations and return the result in array
$result[$row['id']] = $this->doSomething();
}//endforeach;
return $result;
}
I am not sure why you are keeping this object there itself. Any reuse ? the probably paginate and do :-)

Categories