I'm trying to populate a table from another one only if the day is a weekend, but when i try to fetch my results into a php array, it says that i'm fetching a non-object, and this error began when i added my where clause that tries to pick only weekend days. If someone could take a look and correct me, my code is:
EDITed
$con->query("INSERT INTO eventos_dias SELECT DATE(inicio_periodo),'1','0','0','0' FROM eleva WHERE HOUR(inicio_periodo) BETWEEN 0 AND 6 AND WEEKDAY('inicio_periodo') BETWEEN 5 AND 6")
$query=$con->query("SELECT Data, Sum(0h_6h) as sum0_6,Sum(6h_12h),Sum(12h_18h),Sum(18h_24h) FROM evnetos_dias
GROUP BY Data
ORDER BY Data ASC")
while($row->$query->fetch(PDO::FETCH_ASSOC)) //this line contains the error
{
$dados0_6_fds[] = $row['sum0_6'];
}
Ideas are welcome too!
You can't have a WHERE in an INSERT query. Do your date filtering at the PHP level and simply don't run the query at all if it's the weekend:
if ($is_not_weekend);
$con->query('INSERT ...');
}
INSERT INTO eventos_dias(put the columns in here)
SELECT DATE(inicio_periodo),'1','0','0','0'
FROM eleva
WHERE HOUR(inicio_periodo) BETWEEN 0 AND 6
AND WEEKDAY('inicio_periodo') BETWEEN 5 AND 6
Always a good idea to develop your queries with a suitable tool until (and possible still after) you get the hang of sql.
are you sure that
while($row->$query->fetch(PDO::FETCH_ASSOC))
is correct? should it not be
while($row = $query->fetch(PDO::FETCH_ASSOC))
and for clarification (as I can't comment on anything but my own posts) that insert statement works fine, as the where clause is for the select.
Related
ok; this has been frying my brain for hours. I think I might need a sub query, but I'm not that advanced at this kind of thing so any help or pointers in the right direction would be greatly appreciated.
Here's the Query I have....
$query = "SELECT * FROM events WHERE event_type = 'Christmas Listings' AND event_active='Yes' ORDER BY event_date ASC LIMIT 5";
$result= mysql_query($query);
OK... now for the plain english bit on what I want to achieve (to understand what I'm trying to achieve):
I want to check the event type ('event_type') is what I'm getting (ie. Christmas Listings) as there are multiple types in this column.
I want to check the event is active ('event_active') is Yes(the data in this field is Yes/No).
I want to order them by the ('event_date') ASC (the data in this field is yyyy-mm-dd) so they show the latest entry by its date from the DB.
I want to LIMIT (or in some way control the output) the results to only have 5 results displayed when running this kind of query through a WHILE statement.
OK, this all works BUT; when I get to the actual output display, i'm having a shaky output in how many results are actually display... What happens is if I have multiple events which are switched off, as in event_active is 'Off' then its almost like the argument is counting from the all the results that are (including event_active='Off') and consequently not showing how I expect them to display?
Hope this makes sense.... Any help would be gratefully received.
SELECT *
FROM events
WHERE event_type = 'Christmas Listings' AND event_active='Yes'
ORDER BY event_date
LIMIT 0, 5
so your statement is easyer to read..
You shoul use 1 / 0 instead of Yes / no
The Limit does not count all lines!
First step - doing the query including WHERE
Second step - ORDER BY
Third step - LIMIT
If you have set an index on the colum you sort. The sort will stop after 5 lines,
also means - it get faster
The ASC in the ORDER BY command is not necessary, because ASC is default
I am really not sure what you are asking, but LIMIT works as follows:
The LIMIT means that after your query is done, and ALL WHERE statements are processed, only the first 5 are returned.
ALl results where event_active is not 'Yes' will not be shown, and disregarded in everything.
This result is the same as a result where you would do the query without the limit, and just look at the first 5 lines.
That query should be fine. I'd check your data set (or even better, post it!). You might want to look into normalizing the database too. It'll help you out in the future.
The problem, I think, is with your 'event_active'.
MySQL uses 0 and 1 to indicate whether the field is true/false, yes/no, on/off. Try using 0 and 1 in your SELECT statement unless the field type on that field is VARCHAR and you actually are using those words.
I'm running on IBM i (an AS/400) V7R2, PHP v5.6.5, Zend Server v8.0.2.
I have a query which takes less than a second to execute from iNavigator. When I run the same query from a PHP script and then loop through it using:
$numRows = 0;
while ($row = db2_fetch_assoc($stmt))
{
//Do stuff
$numRows++;
}
echo $numRows++;
$numRows ends up only being a fraction of the expected result set and I get this error in the Zend logs:
PHP Warning: db2_fetch_assoc(): Fetch Failure in /path/to/script.php on line XXX
Note that the value of $numRows varies every time I run it. It is almost like it is timing out and ending before it can iterate through all of the result sets, but the page loads in seconds. Outside of results missing from the result set everything seems to function and load perfectly fine on the page.
Does anyone know what might be contributing to this behavior?
Is it possible that the data has errors? One possibility is decimal data errors.
#Buck Calabro got me on the right track. The issue wasn't decimal data errors but rather a sub-query in the view definition which was returning more than 1 row. So it was a "Result of select more than one row" error.
If I did a simple SELECT * FROM VIEW1 in iNavigator or PHP everything seemed to come up fine. It wasn't until I either ran the mentioned query in STRSQL or ran the view definition manually as if it weren't part of a view in iNavigator that the error would be reported.
To help future users here is basically what was happening.
TABLEA contains a single column with 10 rows.
I write a view such as this:
CREATE VIEW VIEWA (COL1, COL2, COL3)
AS SELECT 1, 2, (
SELECT * FROM TABLEA
);
The sub-select is returning 10 rows and the DB engine doesn't know how to handle it. If instead you add FETCH FIRST 1 ROW ONLY as part of the sub-query the error is fixed. That isn't to say logically you will get the correct results though, since you may need the 2nd row not the first. Second it would also be suggested you specify an ORDER BY and/or WHERE clause to ensure the first (and only) row returned would be what you want.
So far everytime i use to make a select query using pdo, i used a while loop to echo all the result. I never has a single problem. But what I am looking to do know is just echo one record. Let's say the record of the 23rd line of my table. So what I a doing is the following but i have this error: Notice: Undefined offset: 23 in /myFilePath/file.php
$qry_que= $connexion->query('SELECT * FROM table ORDER BY somefield';
$row = $qry_que->fetch(PDO::FETCH_ASSOC);
echo $row[23]['somefield'];
Do note that my table has more than 100 lines... Thank you in advance for your help. Cheers. Marc.
You cannot get the 24th row by doing $row[23].
You'll have to use a WHERE clause in your SQL query in order to get only the row you want.
Moreover, it will be a lot better on a performance point of view (think about your query when your database has 10 millions rows...)
We currently have some php code that allows an end user to update records in our database by filling out a few fields on a form. The database has a field called sequentialNumber, and the user can enter a starting number and ending number, and an update query runs in the background on all records with a sequentialNumber between the starting and ending numbers. This is a pretty quick query.
We've been running into some problems lately where people are trying to update records that don't exist. Now, this isn't an issue on the database end, but they want to be notified if records don't exist, and if so, which ones don't exist.
The only way I can think of to do this is to run a select query in a loop:
for ($i=$startNum; $i<=$endNum; $i++) {
//run select query: select sequentialNumber from myTable where sequentialNumber = $startNum;
}
The problem is, our shared host has a timeout limit on scripts, and if the sequentialNumber batch is large enough, the script will time out. Is there a better way of checking for the existence of the records before running the update query?
EDIT:
It just occurred to me that I could do another kind of test: get the number of records they're trying to update ($endNum - $startNum), and then do a count query:
select count(sequentialNumber) where sequentialNumber between $startNum and $endNum
If the result of the query is not the same as the value of the subtraction, then we know that all the records aren't there. It wouldn't be able to tell us WHICH ones aren't there, but at least we'd know something wasn't as expected. Is this a valid way to do things?
You could try
select sequentialNumber from myTable where sequentialNumber between $startNum and $endNum
This will return all known numbers in that range. Then you can use the array_search function to find out if a certain number is known or not. This should be faster than doing a lot of queries to the db.
var count = mysql_fetch_array(mysql_query('SELECT count(*) FROM x WHERE id>startNum and id<endNum'));
var modified = mysql_affected_rows(mysql_query('UPDATE x SET col='value' WHERE id>startNum and id<endNum'));
if (count[0] > modified) {
// panic now
}
I got some help with gettin the number of rows returned from mysql, and it works fine...
BUT, how do I get the number of rows with a certain field value?
Do I have to make a new Mysql search query?
Here is the code where I query mysql and display in a table using fetch_array... Also, Im using mysql_num_rows to get number of rows.
So how do I get number of rows with certain field value also?
$qry_result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result))
Thanks for all help
OBSERVE: Im trying to avoid using another SELECT WHERE clause...
Is there a way to do what I want withouth another search?
In your query, you can use the where clause. (select * from table where column1 = 'value')
Another option would be to have a counter variable that you increment in your while loop:
$counter = 0;
while($row = mysql_fetch_array($qry_result))
{
if($row[0] == "value")
$counter++;
}
After you have this counter, reset the result set using mysql_data_seek($qry_result, 0); and then continue with your original while loop.
There are several ways to reach this, either run additional queries against MySQL or use programm logic to calculate what you need while iterating over the array.
Fetching the number of rows from MySQL is a task that has several solutions as well. You could blindly call SELECT count(*) FROM table WHERE foo = bar, or use the more advanced SQL_CALC_FOUND_ROWS variable of the database.
If you could explain yourself better, I would be glad to provide a good solution!
OBSERVE: Im trying to avoid using another SELECT WHERE clause... Is there a way to do what I want withouth another search?
I'm curious why you don't want to use another SELECT WHERE clause?
From what I interpret of your question, you are asking to have the number of rows of a given query AND, a count of unique variables?
ex:
NAME AGE
Joe 15
Simon 13
Simon 16
Joe 21
Mary 15
Joe 28
Your row count would be 6 and your count (that you are requesting) would be:
Joe x 3
Simon x 2
Mary x 1
If that is what you are asking, why not use 2 queries, 1 for your set of data, and another query where you GROUP BY 'name' and return only UNIQUE 'name' results? That would get you a count of your "certain fields".
Then again correct me if I miunderstood your question.