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.
Related
I have a query like this
select fname,joined_date from employees where id=1
currently the date format I'm using to display this returned employee details is Y-m-d.
But now I need to convert the default mysql format Y-m-d to d/m/Y(in all date information display fields).
For me it's very very difficult to go through all the files to do the date format conversion.
So I thought of doing some thing like this in my database class.I have a function like this in my database class
function fetch($res){
$row = mysql_fetch_assoc($res);
foreach($row as $key=>$value){
if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value))
$row[$key] = date('d/m/Y',strtotime($value));
}
return $row;
}//end function
and i'm using this function like this
$row = $db->fetch($res);
or
while($row = $db->fetch($res)){...}
I'm getting the expected output,but with an error message
invalid argument for foreach
it looks like the fetch function code executed (total_num_rows + 1) times
If I use for loop instead of foreach, getting undefined offset error
currently I'm using some thing like this to escape
if(is_array($row)){...}
when i look for the type $res,
it showed
resource(1st iteration),resource(2nd)
for $row array
array(1st iteration),boolean(2nd)
Can anybody tell me why it's happening?
Or is there a better way to do this?
Thanks in advance.
When you reach the end of the results, mysql_fetch_assoc() returns false. You need to check for that case:
function fetch($res){
$row = mysql_fetch_assoc($res);
if ($row) {
foreach($row as $key=>$value){
if(preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/',$value)){
$row[$key] = date('d/m/Y',strtotime($value));
}
}
}
return $row;
}
if you want this format for ex: June 19, 2015
use this:
date("F d, Y",strtotime($myrow['date']));
where $myrow['date'] is what you are fetching from mysql row wise
check this link for further assistance: http://erikastokes.com/mysql-help/display-mysql-dates-in-other-formats.php
It is easier to have you convert the date to the desired format already in the MySQL command.
example:
SELECT *, DATE_FORMAT(date, "%m-%d-%y") AS date FROM my_table;
I got an SQL error message when activating a rule with some Php validation.
The goal of that rule is to check if a user has voted more than 2 times in the last 24 hours.
Here is the code I used:
// Configure your settings:
$daily_limit = 2;
$content_type = 'node';
$day = strtotime(date('Y-m-d'))-1;
// Load the active user account
global $user;
// Drupal has a security feature called the Database Abstraction Layer.
// You have to build DB queries with variables that are defined in an array.
// Define the query string, where ":drupaluid" etc. are arbitrary placeholders
$query = 'SELECT * FROM votingapi_vote WHERE uid=:drupaluid AND content_type=:drupaltype AND timestamp > :day';
// Define each placeholder
$variables = array(':drupaluid' => $user->uid, ':drupaltype' => $content_type, ':day' => $day);
// Query the Drupal database
$result = db_query($query, $variables);
// Count the number of rows returned from the Drupal database
// From: http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7
$nodecount = $result->rowCount();
// Set the flag as to whether this Rule is effective or not
if ( $nodecount >= $daily_limit) {
return TRUE; // You will be over the accepted quota
} else {
return FALSE; // Still got room. Allow the new node.
}
I tried to debug the query but even a simple query like $query = 'SELECT * FROM votingapi_vote WHERE uid = 1 is not working in Php whereas It work in mysql console.
Does anyone see this error?
DatabaseStatementInterface::rowCount specifically returns
The number of rows affected by the last DELETE, INSERT, or UPDATE statement executed.
It's not used to retrieve the count of a result set. To do that use a count query, or simply use PHP functions
$result = db_query($query, $variables)->fetchAll();
$nodecount = count($result);
I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.
I'm trying to make a php tool that will get the users registered between specific dates. However, I'm running into a strange issue. The query doesn't seem to recognize all of the records in the table. Let me explain.
Here's the php code:
function getRegistrations($startDate,$endDate) {
//echo $startDate;
//echo $endDate;
$startDate = date('Y-m-d H:i:s',$startDate);
$endDate = date('Y-m-d H:i:s',$endDate);
$query = "SELECT * FROM database.user WHERE created_date>='".$startDate."' AND created_date<='".$endDate."';";
$result = mysql_query($query);
$data = array();
$data['query'] = $query;
$data['content'] = array();
if($result) {
$data['status'] = 1;
$data['message'] = "Success";
}
$count = 0;
$data['num_rows'] = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$data['content'][$row['user_id']] = $row;
$count++;
}
$data['count'] = $count;
echo json_encode($data);
}
When I run the query in the mysql workbench, it works just fine. However, when I'm running it through php, it seems to ignore every record after a certain one. I can see all the records up to user_id=243, and then it ends. num_rows and count are still equal, and they're equal to the length of content. However, if I run the query directly from the mysql workbench, I can see that it should be much higher.
Also, it's always stopping at the same record, regardless of the dates. If I choose an early start date, then it might return 50 records, but it still stops at the same one.
Does anyone have any ideas? Although I'm pretty new to MySQL, I haven't been able to find anyone with a similar problem.
Thanks in advance!
delete that one particular row. simple as that. reinsert it and see if the problem persists.
mysql_query() says query string should not end with a semicolon. Your query should be
$query = "SELECT * FROM database.user WHERE created_date>='".$startDate."' AND created_date<='".$endDate."'";
Hallo,
I have sort of daily random image system build with Codeigniter and Doctrine.
There is key function, which returns daily image or sets new one. I am using recursive calling, but sometimes are two images selected for one day.
class Daily extends Controller {
function find_daily(){
$connection = Doctrine_Manager::connection();
$connection->setCharset('utf8');
$q = Doctrine_Query::create()
->select('COUNT(id) as dailycount')
->from('Image')
->where('daily_date = ?',date("Y-m-d"));
$set = $q->execute();
if( $set[0]->dailycount != 0 ){ //theres one or more for today
$q = Doctrine_Query::create()
->select('id')
->from('Image')
->where('daily_date = ?',date("Y-m-d"))
->limit(1);
$set = $q->execute();
$i = Doctrine::getTable('Image')->findOneById($set[0]["id"]);
return $i;
}else { // none image selected with today date
$q = Doctrine_Query::create()
->select('id')
->from('Image')
->where('daily_date = ?', "0000-00-00")
->andWhere("dir =?","queue")
->orderBy("rand()")
->limit(1);
$set = $q->execute();
$i = Doctrine::getTable('Image')->findOneById($set[0]["id"]);
$i->daily_date = date("Y-m-d");
$i->dir = "archive";
$i->save();
$this -> find_daily();
};
}
...
I think theres some stupid mistake.. maybe calling something like "Doctrine::doAllAndClear" before $this -> find_daily(); or I forget something...
Or is better not to use recursive calls?
Thanks.
Well, I've not tested this at all, but I'd probably be more likely to write your code more like this; hopefully this will give you some ideas:
function find_daily() {
$connection = Doctrine_Manager::connection();
$connection->setCharset('utf8');
// Make sure "today" doesn't change while the script runs
$today = date("Y-m-d");
// Find an image with today's date.
$q = Doctrine_Query::create()
->from('Image')
->where('daily_date = ?', $today)
->limit(1);
$image = $q->fetchOne();
if (!$image) {
// There was no image with today's date, so pick one from the queue at random instead.
$q = Doctrine_Query::create()
->from('Image')
->where('daily_date = ?', "0000-00-00")
->andWhere("dir =?","queue")
->orderBy("rand()")
->limit(1);
$image = $q->fetchOne();
// ToDo: Cope with there being no image in the queue
$image->setDailyDate($today);
$image->setDir("archive");
$image->save();
}
return $image;
}
However, you need to think about what happens if two people hit your script at the same time. In that case, they may both fetch a new image for the day (because they could each run the first SELECT at the same time, and both get a result that says there's no daily image yet.)
To avoid that, I'd guess you'd want to wrap this in a transaction, and set a transaction isolation level such that the first caller of the function "wins" the race condition, and subsequent callers block until the update is safely saved. Not entirely sure how you'd do that with Doctrine, but it shouldn't be hard.
Checking the manual, a beginTransaction() at the start, a commit() at the end, and a setup before everything else involving $tx = $conn->transaction; $tx->setIsolation('SERIALIZABLE'); (otherwise two users could probably still run the SELECT at once) would probably be all you need, but you might want to wait for someone who really knows Doctrine to comment on that...
I also saved "today"'s date at the start of the script, otherwise there's a danger of it being different during the SELECT and the later UPDATE, if the script runs across midnight.