Zend db select how to know return zero rows? - zend-framework

This is my code:
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
if(!$query) {
return false;
} else {
$row = $this->fetchRow($query);
$row = $row->toArray();
return $row;
}
}
But sometimes, I receive
Fatal error: Call to a member function toArray() on a non-object in...
Is it right to use if(!$query) to check the existing rows in DB?

Change your code to this
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(!$row) {
return false;
} else {
return $row->toArray();
}
}
Because $query object will always be created irrespective $url matches record or not hence will always pass if condition .

Is it right to use if(!$query) to check the existing rows in DB ?
No, you should evaluate the result of fetchRow to determine if there are results, fetchRow either returns a Zend_Db_Table_Row or null if no rows are found.
public function is_existing($url) {
$query = $this->select()
->where("url=?",$url);
$row = $this->fetchRow($query);
if(is_null($row)) {
return false;
} else {
return $row->toArray();
}
}

Related

Laravel returning LogicException "must return a relationship instance."

I am getting the error whenever the function getCips is being called:
App\Models\Employee::getAllCips must return a relationship instance.
The function that is causing this error is:
private function getCips($user, $page, $search){
if($page == null)$page = 1;
$count = 7;
$cips = null;
if(get_class($user) == User::class)
{
$cips = Visitable::all()->whereNotNull('cip');
}else{
$cips = $user->getAllCips(); //The error is caused because of this line.
}
if($search!=null){
$cips = $cips->filter(function($cip, $i)use($search){
return strpos($cip->name, $search)!==false||strpos($cip->email, $search)!==false||strpos($cip->phone, $search)!==false||strpos($cip->location->name, $search)!==false||strpos($cip->cip->Associated_hospital, $search)!==false;
});
}
$lastPage = ($cips->count()%$count == 0)? intdiv($cips->count(), $count):intdiv($cips->count(), $count)+1;
$page = ($cips->count() == 0)?0:intval($page);
return ["cips"=>$cips->values()->skip(($page-1)*$count)->take($count)->all(),"lastPage"=>$lastPage, "currentPage"=>$page];
}
As marked in the line of code above, the $user is an instance of Employee class.
Now the function getAllCips() in class Employee is as:
public function getAllCips():Collection{
$allCips = $this->headQuarter->getAllCips();
foreach($this->subordinates as $subordinate){
$allCips = $allCips->concat($subordinate->getAllCips);
}
return $allCips;
}
I am using Laravel 8. It would be very helpful if anybody could point out what I am doing wrong here.

Codeigniter Call to a member function where() on bool

I tried to set seen to any contact data in database, but when i try that:
public function showMessage($id){
$this->load->model('Message_Model');
$messageData = $this->Message_Model->selectMessage($id);
if($messageData[0]->messageIsSeen == 0){
$this->Message_Model->setSeenToMessage($id);
}
$data = array('messageData' => $messageData[0]);
$this->load->view('Back/MessageDetail', $data);
}
Model:
function setSeenToMessage($id){
$this->db->update('messages', array('messageIsSeen' => 1))->where('messageId', $id);
return 1;
}
It throws that error
i solved it like this change
function setSeenToMessage($id){
$this->db
->where('messageId', $id);
->update('messages', array('messageIsSeen' => 1))
return 1;
}
nevertheless, still i don't know how did it works

Zend2 TableGateway: how to retrieve a set of data

I have a ContactsTable.php module and an function like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row record");
}
return $row;
}
which is ok, but it only returns one row.
The problem is in my database I have multiple records with the same Last Name, so my question is:
How can I return a set of data?
I tried this:
$where = new Where();
$where->like('last_name', $last_name);
$resultSet = $this->tableGateway->select($where);
return $resultSet;
but it doesn't work.
Your first function should work as you expect, just remove line
$row = $rowset->current();
So, complete function should look like this:
public function getContactsByLastName($last_name){
$rowset = $this->tableGateway->select(array('last_name' => $last_name));
foreach ($rowset as $row) {
echo $row['id'] . PHP_EOL;
}
}
More info you can find in documentation http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html
You can use the resultset to get array of rows:
public function getContactsByLastName($last_name) {
$select = new Select();
$select->from(array('u' => 'tbl_users'))
->where(array('u.last_name' => $last_name));
$statement = $this->adapter->createStatement();
$select->prepareStatement($this->adapter, $statement);
$result = $statement->execute();
$rows = array();
if ($result->count()) {
$rows = new ResultSet();
return $rows->initialize($result)->toArray();
}
return $rows;
}
Its working for me.

convert from mysql to mysqli problem

I recently changed from using mysql to msqli, since then the CRUD functions have all stopped working properly. Please can someone point me in the right direction. Here is my code. sorry for my bad english.
public function create() {
global $database;
$attributes = $this->sanitised_attributes();
$sql = "INSERT INTO ".self::$table_name."(";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
$this->id = $database->insert_id();
return true;
} else {
return false;
}
}
Here is the class
class mysqliDatabase {
private $connection;
public $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
function __construct() {
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists("mysqli_real_escape_string");
}
public function open_connection(){
$this->connection = new mysqli(DB_HOST,DB_USER,DB_PASSWORD);
if(!$this->connection) {
die("Database connection failed: " . mysqli_error());
} else {
$db_select = mysqli_select_db($this->connection,'*****');
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
} else { echo "connected";}
}
}
public function close_connection(){
if(isset($this->connection)) {
mysqli_close($this->connection);
unset($this->connection);
}
}
public function query($sql) {
$this->last_query = $sql;
$result = mysqli_real_query($this->connection, $sql);
$this->confirm_query($result);
return $result;
}
public function escape_value($value) {
if($this->real_escape_string_exists) {
//undo any magic quote effects so mysqli_real_escape can do the work
if($this->magic_quotes_active){ $value = stripslashes($value);}
$value = mysqli_escape_string($this->connection, $value);
} else {
//if magic quotes aren't already on then add slashes manually
if(!$this->magic_quotes_active) { $value = addslashes($value);
}
//if magic quotes are active, then the slashes already exist
}
return $value;
}
public function fetch_array($result_set) {
return mysqli_fetch_array($result_set);
}
public function num_rows($result_set) {
return mysqli_num_rows($result_set);
}
public function insert_id() {
//get the last id inserted over the current db connection
return mysqli_insert_id($this->connection);
}
public function affected_rows() {
return mysqli_affected_rows($this->connection);
}
private function confirm_query($result) {
if(!$result) {
$output = "Database query failed " . mysqli_error($this->connection) . "<br
/><br />";
$output .= "last SQL query: " . $this->last_query;
die($output);
}
}
The problem is not in this function, but in the database class. You would need to share that one to be able to get help.

Database expression not used in query

Can anyone tell me why my expression is not used in the query below?
SELECT accountreset.* FROM accountreset WHERE (reset_id = '34') LIMIT 1
public function findByResetId($resetId, $model = null) {
$result = null;
if (isset($resetId)) {
$select = $this->getDao()->select(
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);
$select->where('reset_id = ?', $resetId);
$row = $this->getDao()->fetchRow($select);
if (null != $row) {
if (!($model instanceof Stage5_Model_PasswordResetter)) {
$model = new Stage5_Model_PasswordResetter();
}
// vul het model object
$model->setResetId($row->reset_id);
$model->setUserId($row->user_id);
$model->setExpiration($row->expiration);
$result = $model;
}
}
return $result;
}
Your Zend_Db_Expr should go into from() method instead of select()
$select = $this->getDao()
->select()
->from(
$this->getDao()->info('name'),
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);