I am trying to query an SQL table, and then have all the values from one column (it's a "tinyint(1)") added up and then printed, using array_sum. (Currently there are only two rows).
When both rows have a "1" in that column, it gives 2, the correct answer. And when they are both "0" it gives 0, correct again. But when one is "1" and one "0" it gives 2, not 1.
This is my code
$con = mysql_connect("XXX","XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXX_test", $con);
$day = $_GET["day"];
$query = mysql_query("SELECT $day FROM sites");
if (!$query)
{
die('Could not query: ' . mysql_error());
}
$rows = mysql_fetch_array($query);
echo array_sum($rows);
mysql_close($con);
?>
Thanks for any help.
--UPDATE--
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}
This in fact never works correctly.
$rows = mysql_fetch_array($query);
That line only ever fetches the first row. The second row is never retrieved.
The reason it gives 2 using array_sum is that mysql_fetch_array gets the result in two different formats, with keys both by name and number. So you'll get something like this:
array(
0 => '1',
'Tuesday' => '1'
)
Obviously this will always be 2 or 0.
You should almost certainly do a count on the DB server:
SELECT COUNT(*) FROM sites WHERE $day=1
Note, however, that your biggest current problem is the enormous gaping SQL injection hole. Sanitise your input.
mysql_fetch_array() only fetches one row at a time. You need to fetch the rows in a while loop. Then you can either append the results to an array and sum those, or sum them in the loop. You can also SUM in mysql anyway, so you might look into using that.
I'm also obligated to suggest that you use PDO or some other DB wrapper instead of mysql_. You also need to escape variables you use in queries under most circumstances, especially if they come from _GET.
I would suggest doing it in the mysql query:
SELECT SUM($day) FROM sites
also, please escape the $day variable.
More of a comment:
array_sum can not work with the array you're passing to it. You need to pass an array for what the function actually works, like array(1, 2, 3) which will give you 6 then.
Next to that, let MySQL itself calculate the SUM (or COUNT?), so it's easier to handle in your script as others have posted.
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}
Related
I am having some trouble displaying a single field from the db based on an ID number.
I want to trying to display the "C_Type_of_Referral" if the ID matches. I am sure the code is a mess of crap but I am still at the VERY early stages of learning how to do things in mysql and php.
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = '70'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($C_Type_of_Referral) = mysql_fetch_array($result);
Then I am trying to display the result using the code below:
echo ((isset ($_POST['C_Type_of_Referral']) && $_POST['C_Type_of_Referral'] == 'AS') || ($C_Type_of_Referral == 'AS'));
The code above returns the value of 1.
echo ($_POST['C_Type_of_Referral']);
The code above returns nothing.
Where am I going wrong?
Thanks for any help!
Let me start with: Use mysqli instead of mysql, especially when you are starting. Mysql is getting outdate, so start with the right one :)
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = 70 LIMIT 1";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$fetch = mysql_fetch_assoc($result);
echo $fetch['C_Type_of_Referral']; // <- this is what you are looking for
if( $fetch['C_Type_of_Referral']=='AS'){ echo 'AdServices'; }
elseif( $fetch['C_Type_of_Referral']=='VS'){ echo 'VisServices'; }
else{ echo 'Nothing of the kind'; }
Things I've done:
- removed quotes arround 70. Integers should not use quotes.
- Added 'limit 1'. This will speed things up in the long run. If you want 1 line, use limit 1
- Changed fetch_array to fetch_assoc ( you'll have to find out why yourself ;) )
Small note: keep table and columnnames lowercase, some systems might give you troubles when you use uppercase characters
I know this is something simple. I'm just forgetting something.
I'm counting the values of the rows in the "numberattending" column of my database.
When I run the SQL statement
SELECT COUNT(numberattending) AS Total FROM RSVP
in the mySQL window I get the total I'm looking for.
When I try to extract that value and echo "num_seats" I get "Resource id #3"
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
echo $num_seats;
What I'm I missing?
Thanks for any help ahead of time.
$num_seats represents a MySQL Resource, not the value of the field selected. You'll need to use either mysql_fetch_array() or mysql_fetch_object() depending on which you prefer.
For example:
$number = mysql_fetch_array($num_seats);
echo $number['Total'];
It's also worth noting that the mysql_* family of functions are now deprecated, and you should really be using MySQLi or PDO.
You need to loop through the result sets:
From the PHP site:
// Use result // Attempting to print $result won't allow access to
information in the resource // One of the mysql result functions must
be used // See also mysql_result(), mysql_fetch_array(),
mysql_fetch_row(), etc.
$num_seats = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
while ($row = mysql_fetch_assoc($num_seats )) {
echo $row['total'];
}
PS: As others will surely tell you, use of the mysql* functions have been deprecated. Look for the mysqli functions instead.
Try
$query = mysql_query("SELECT COUNT(numberattending) AS Total FROM RSVP", $connection);
$result = mysql_fetch_row($query);
echo $result['Total'];
I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)
I get the following error when i try to display index.php
Warning: mysql_numrows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\cards\index.php on line 18
I can't tell if I'm not connecting to the database correctly or if thre is some other error. Basically I'm trying to display 3 random lines of data from my table "cards". The column in the table that I want to display the data from is "playerName". I'm not worried about formatting the data yet. Code is below:
<?php
include_once 'header.php';
require_once 'config.php';
$con = mysql_pconnect("localhost","*****","*****");
mysql_select_db("USE cards",$con);
$cards=0;
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT * FROM cards ORDER BY RAND() LIMIT 3";
$results = mysql_query($sql);
$array = mysql_fetch_array($results);
$num=mysql_num_rows($results);
$i=0;
while ($i < $num) {
echo $rows['playerName'];
$i++;
}
include_once 'footer.php';
?>
I know this is probably a simple newbie question, but I appreciate the help.
Your mysql_select_db call should take only the database name as first argument, not the entire USE statement. Most likely it silently fails and does not select the cards database. Then the query fails (again, silently) returning false.
Also, it's mysql_num_rows (not mysql_numrows).
Manual: http://php.net/manual/en/function.mysql-num-rows.php
Two things, echoing an array wont print it(echo $results;) instead use print_r($results) or var_dump($results) and the other thing, I reckon the error is caused be cause no results are returned, but if you use var_dump or print_r you will be able to verify whether that is the case :)
also there is a typo here: $con = mysql_pconnect("localhost","jalexander","brunswick3"); remove the p from connect :)
Also, you might want to replace your db credentials with asterixes on here :)
Finally, you declare the variable cards but never use it?
In fact one more, change $rows[playerName] to $rows['playerName']
To get different rows instead of using a while loop you can use a foreach like so:
foreach($array as $row){
echo $row['playerName'];
}
Or to do it using a while loop use
$i=0;
while ($i < $num) {
echo $rows[$i]['playerName'];
$i++;
}
It did not work in your current code because you was not looping through the elements of the array, just echoing the same one each time
HI everyone i tried for 3 days and i'm not able to solve this problem. This is the codes and i have went through it again and again but i found no errors. I tried at a blank page and it worked but when i put it inside the calendar it has the syntax error. Thanks a million for whoever who can assist.
/** QUERY THE DATABASE FOR AN ENTRY FOR THIS DAY !! IF MATCHES FOUND, PRINT THEM !! **/
$testquery = mysql_query("SELECT orgid FROM sub WHERE userid='$userid'");
while($row4 = mysql_fetch_assoc($testquery))
{
$org = $row4['orgid'];
echo "$org<br>";
$test2 = mysql_query("SELECT nameevent FROM event WHERE `userid`=$org AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'") or die(mysql_error());
while($row5=mysql_fetch_assoc($test2))
{
$namethis = $row5['nameevent'];
$calendar.=$namethis;
}
}
First question: what calendar are you talking about?
And here are my 2-cents: does the EXTRACT function returns a string or a number?
Are the "backticks" (userid) really in your query? Try to strip them off.
Bye!
It's a guess, given that you haven't provided the error message you're seeing, but I imagine that userid is a text field and so the value $org in the WHERE clause needs quotes around it. I say this as the commented out testquery has quotes around the userid field, although I appreciate that it works on a different table. Anyway try this:
SELECT nameevent FROM event WHERE userid='$org' AND EXTRACT(YEAR FROM startdate)='2010' AND EXTRACT(MONTH FROM startdate)='08' AND EXTRACT(DAY FROM startdate)='15'
In such cases it's often useful to echo the sql statement and run it using a database client
First step in debugging problems like this, is to print out the acutal statement you are running. I don't know PHP, but can you first build up the SQL and then print it before calling mysql_query()?
EXTRACT() returns a number not a character value, so you don't need the single quotes when comparing EXTRACT(YEAR FROM startdate) = 2010, but I doubt that this would throw an error (unlike in other databases) but there might be a system configuration that does this.
Another thing that looks a bit strange by just looking at the names of your columns/variables: you are first retrieving a column orgid from the user table. But you compare that to the userid column in the event table. Shouldn't you also be using $userid to retrieve from the event table?
Also in the first query you are putting single quotes around $userid while you are not doing that for the userid column in the event table. Is userid a number or a string? Numbers don't need single quotes.
Any of the mysql_* functions can fail. You have to test all the return values and if one of them indicates an error (usually when the function returns false) your script has to handle it somehow.
E.g. in your query
mysql_query("SELECT orgid FROM sub WHERE userid='$userid'")
you mix a parameter into the sql statement. Have you assured that this value (the value of $userid) is secure for this purpose? see http://en.wikipedia.org/wiki/SQL_injection
You can use a JOIN statement two combine your two sql queryies into one.
see also:
http://docs.php.net/mysql_error
http://docs.php.net/mysql_real_escape_string
http://www.w3schools.com/sql/sql_join.asp
Example of rudimentary error handling:
$mysql = mysql_connect('Fill in', 'the correct', 'values here');
if ( !$mysql ) { // some went wrong, error hanlding here
echo 'connection failed. ', mysql_error();
return;
}
$result = mysql_select_db('dbname', $mysql);
if (!$result ) {
echo 'select_db failed. ', mysql_error($mysql);
return;
}
// Is it safe to use $userid as a parmeter within an sql statement?
// see http://docs.php.net/mysql_real_escape_string
$sql = "SELECT orgid FROM sub WHERE userid='$userid'";
$testquery = mysql_query($sql, $mysql);
if (!$testquery ) {
echo 'query failed. ', mysql_error($mysql), "<br />\n";
echo 'query=<pre>', $sql, '</pre>';
return;
}