I have made a few Laravel application (Mainly Laravel Zero) and I have not seen this type of issue before.
I have an array which consists of 3 strings, and 3 indexes. The plan is to foreach through this array to check if the values already exist in the database, I have never had issues with Eloquent before but it appears to be having some unexpected results?
foreach ($transaction as $transactions)
{
// Check if TX exists
$exists = $database->where('txid', '=', $transactions['txid'])->toSql();
echo $exists . "\n";
}
Each time it goes around the loop, the query changes - the first iteration returns true when using exists() but anything after that is false when it should be true.
Output results of toSql();
select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ? and `txid` = ?
Expected results of toSql();
select * from `transactions_incoming` where `txid` = ?
select * from `transactions_incoming` where `txid` = ?
What is $database in your case? make sure $database is initialized every time your loop is executed as new for example
assuming your $database is transaction's model object
foreach ($transaction as $transactions)
{
$database = new Transaction();
// Check if TX exists
$exists = $database->where('txid', '=', $transactions['txid'])->toSql();
echo $exists . "\n";
}
Related
the task is to save the $model->image with row id in it.
to anticipate the next autoincrement id i use the query below. mysql returns right result, but when i try to save this query result in model it saves it like 'Array' string.
For example : article_Array_1516534305.png instead of article_13_1516534305.png
i tried to use array_shift() function, but result is the same
$connection = Yii::$app->getDb();
$dbName = $this->getDsnAttribute('dbname', Yii::$app->getDb()->dsn);
$query = new Query;
$query->select('AUTO_INCREMENT')
->from('information_schema.TABLES')
->where("TABLE_SCHEMA = '".$dbName."'")
->andWhere("TABLE_NAME = '".$this->tableName()."'");
$id = $query->one();
$this->image = 'article_'.$id.'_'.time(). '.' . $image->extension;
With $query->one() you get a single model
If you need only the column value you should use scalar()
$query->scalar();
http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
http://www.yiiframework.com/doc-2.0/yii-db-query.html#scalar()-detail
or if you want the model however you can use
$id = $query->one();
$id = $id['AUTO_INCREMENT'];
the problem was that i had associated array
$id = $query->one();
$id = $id['AUTO_INCREMENT'];
now it works
I am currently doing a event scheduling module for my system. I want to count all the scheduled events for all months.. For example I have 10 events for this march, then 5 incoming events in April but I am encountering error "A Database Error Occurred"
CONTROLLER
$data['getAll'] = $this->CrudModel->count_all('events');
MODEL
public function count_all($table)
{
// $this->db->select('service');
// $this->db->from($table);
// $this->db->where('date LIKE','%'.$month.'%'); // 2017-03-04
// $num_results = $this->db->count_all_results();
// return $num_results->result();
$query = $this->db->query("SELECT date, service from $table");
foreach ($query->result() as $row)
{
# code...
$date = $row->date;
$service = $row->service;
$date_explode = explode('-', $date);
$year = $date_explode[0];
$month = $date_explode[1];
$day = $date_explode[2];
$service_explode = explode(',', $service);
echo "<pre>";
print_r($date_explode);
print_r($service_explode);
echo "</pre>";
$this->db->like('date',$month); // 2017-03-04
$num_results = $this->db->count_all_results();
}
// return $query->result();
}
Question: Is my query wrong? If yes what is it? Or any other suggestion how to count all the scheduled events?
NOTE: I only used one date.. The scheduled date(Eg. I scheduled the event in 2017-03-04), i dont have end date(cause I used the date input type in html)
you must specify table name
$this->db->count_all_results("table");
Active Record Documentation for count_all_results();
Looks to me like the query is missing a FROM clause and tablename. (Or an inline view query in place of an identifier.)
MySQL (or MariaDB) Server is reporting a syntax error, flagging the the WHERE keyword. MySQL is expecting the statement to have FROM clause, and is not finding it.
The error message reports that an invalid statement was issued, looks like this:
SELECT COUNT(*) AS `numrows` WHERE ...
What's missing is the FROM keyword and a table_name:
SELECT COUNT(*) AS `minimums` FROM some_row_source WHERE ...
^^^^^^^^^^^^^^^^^^^^
Maybe $table is being evaluated as an empty string?
For debugging this, I'd suggest first figuring out which line(s) of code is causing this SQL statement to be executed.
I'm sorry to have to post this, I know it seems similar to other posts, so I ask you to please bear with me...
What I am trying to do: I have a sql query that is in a function, the point of the function is to find if there are TinyInts of a particular value (1 or 0), I am doing a count, and need to just return effectively if it found the value in the specified in the query. What should be coming back is 1 but I only get 0's back...
Here is the whole function:
//return count of VALUES
function getcountsroles($searchParams, $searchCrit){
/// does query, gets results, counts the number and returns that true or false
///this willbe used to show the dashboard user control more efficently.
// $searchParams == column
// $searchCrit == int 1 or 0
//should fetch back the count back from the query
global $db, $dashboard_message_users;
$count_Data=array();
$query = "SELECT COUNT(userID) AS countVal FROM roles WHERE ? = ?";
$stmnt = $db -> prepare($query);
if(!$stmnt){
echo var_dump($stmnt);
}
$stmnt -> bind_param("si", $searchParams, $searchCrit);
if(!$stmnt -> execute()){
$dashboard_message_users = "<p class='alert alert-danger'>The db query faulted.</p>";
}
$result = $stmnt -> get_result();
while ($data = $result->fetch_assoc()){
$count_Data[] = $data;
}
$test = 'userID';
$value = (int)($data['countVal']);
echo var_dump($test);
echo var_dump($searchCrit);
echo var_dump($searchParams);
echo var_dump($value);
echo var_dump($count_Data);
if ($value > 0){
return true;
}else{
return false;
}
}
The calling function sends the column to count the values of, and the the value that we are looking for. when I run the query against the database I get the correct values, I have tested with different columns and values (again 1 or 0)
SELECT COUNT(*) as 'countVal' FROM roles WHERE isUser = 1;
SELECT * FROM roles WHERE isUser = 1;
SELECT * FROM roles;
SELECT COALESCE(COUNT(isUser),0) AS totid FROM roles;
the first one returns 2, the second is all the rows where isUser is value of 1,
third grabs all rows... and the last one was a attempt to see if it was going work... but it still only returns 0 to the result... I have also tried to get the count of rows should be 1, either if true or false... This i getting annoying, Unfortunately I happen to be using mysqli lib and most exampled are for POD or old mysql_PHP, and in OO it seems to not like the prepared statements.
I am positive its something I am doing, I have looked over and over my code and I cant see what the issue is... Maybe if a fresh pair of eyes.
Any time or replies that help me and others out would be greatly appreciated.
Jesse Fender
I'm trying to use an object to count the number of records in my db that meet certain criteria but I can't work out how to make it work. The following code is my count method inside my db connection class:
//Counts the total number of records and returns integer
public function totalCount($fieldname, $tablename, $where = "")
{
$q = "SELECT count(".$fieldname.") FROM "
. $tablename . " " . $where;
$result = $this->mysqli->query($q);
$count = 0;
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$count = $row[0];
}
}
return $count;
}
This code is outside the class:
//New instantiation
$mydb = new myDBC();
//Count the number of transactions for the user...
$count = $mydb->totalCount('amount','transactions','WHERE userid = 13');
//output the number of transactions for the user
print $count;
For some reason this always displays 0, even though my db has thousands of records inside it that should be counted. Grateful for any pointers as to where my syntax isn't right.
Thanks
Does this method returns zero for all tables/fields or you tested only
$mydb->totalCount('amount','transactions','WHERE userid = 13');?
The count counts only NOT NULL values. To count all records pass asterisk to the count function: count(*)
Query execution returning false and it's not going inside if conditions thats why count is always zero
You can use prepared statement to prepare the query and then execute it. And, I don't think that it is essential to pass a field as argument to COUNT.
Anyway, as per your question, this would make a better query.
$q = 'SELECT COUNT( * ) FROM ' . $strTable . ' WHERE ' . $strCond;
Again, since you are using MySQLi, use prepared statements.
Assuming that the mysqli object is already instantiatied (and connected) with the global variable $mysql, here is the code I am trying to work with.
class Listing {
private $mysql;
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
return $info;
}
}
there are several hundred listings in the db and when I call $result->fetch_array() it places in an array the first row in the db.
however when I try to call the object, I can't seem to access more than the first row.
for instance:
$listing_row = new Listing;
while ($listing = $listing_row->getListingInfo()) {
echo $listing[0];
}
this outputs an infinite loop of the same row in the db. Why does it not advance to the next row?
if I move the code:
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
if I move this outside the class, it works exactly as expected outputting a row at a time while looping through the while statement.
Is there a way to write this so that I can keep the fetch_array() call in the class and still loop through the records?
Your object is fundamentally flawed - it's re-running the query every time you call the getListingInfo() method. As well, mysql_fetch_array() does not fetch the entire result set, it only fetches the next row, so your method boils down to:
run query
fetch first row
process first row
return first row
Each call to the object creates a new query, a new result set, and therefore will never be able to fetch the 2nd, 3rd, etc... rows.
Unless your data set is "huge" (ie: bigger than you want to/can set the PHP memory_limit), there's no reason to NOT fetch the entire set and process it all in one go, as shown in Jacob's answer above.
as a side note, the use of stripslashes makes me wonder if your PHP installation has magic_quotes_gpc enabled. This functionality has been long deprecrated and will be removed from PHP whenever v6.0 comes out. If your code runs as is on such an installation, it may trash legitimate escaping in the data. As well, it's generally a poor idea to store encoded/escaped data in the database. The DB should contain a "virgin" copy of the data, and you then process it (escape, quote, etc...) as needed at the point you need the processed version.