Let say that we have the following query:
SELECT DISTINCT COUNT(`users_id`) FROM `users_table`;
this query will return the number of the users from a table. I need to pass this value to a PHP variable. I'm using this:
$sql_result = mysql_query($the_query_from_above) or die(mysql_error());
if($sql_result)
{
$nr_of_users = mysql_fetch_array($sql_result);
}
else
{
$nr_of_users = 0;
}
please correct my code where you think is necessary.
Which is the best approach. How do you recommend to do this ?
Like this:
// Changed the query - there's no need for DISTINCT
// and aliased the count as "num"
$data = mysql_query('SELECT COUNT(`users_id`) AS num FROM `users_table`') or die(mysql_error());
// A COUNT query will always return 1 row
// (unless it fails, in which case we die above)
// Use fetch_assoc for a nice associative array - much easier to use
$row = mysql_fetch_assoc($data);
// Get the number of uses from the array
// 'num' is what we aliased the column as above
$numUsers = $row['num'];
Also, an alternative using mysqli, which you should be using anyway for parameter interpolation:
$statement = $connection->prepare($the_query_from_above);
$statement->execute();
$statement->bind_result($nr_of_users);
$statement->fetch();
Related
For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:
Warning: mysqli_query() expects at least 2 parameters, 1 given
But I only need one parameter. I think I'm totally wrong.
This is the function:
public function GetTotalOfFriends($user_id){
$db = new Db();
$select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
$result = $db->conn->query($select);
$row = mysqli_query($result);
$total = $row[0];
echo $total;
I'm trying to print it out in this way:
$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);
<?php echo $numberoffriends; ?>
You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query.
Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.
The result you got is a mysql_result object, which you need to use to get to the actual data of the query result.
The documentation of this object is here and I suggest that you read it thoroughly.
One possible way to do this is using this:
$resultArray = $result->fetch_row();
This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:
return $resultArray[0];
You could also use any of the other fetch methods if you want your data in a different fashion.
The following function is designed to check whether this row in this tables exists. I know that it does not yet whether I $row or !$row the if function it does not do anything.
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
while($row = mysql_fetch_array($four_zero_four)) {
echo 'no'; die();
}
};
$name is the name field from the row and is working correctly in other functions.
Another way to check whether a row exists is by using the mysql_result function in conjunction with the COUNT function as such:
$query = mysql_query("SELECT COUNT(1) FROM `table` WHERE `field` = 'something'");
$result = mysql_result($query, 0);
When you now print out the $result variable, you will see the amount of rows that are actually being returned by the query. This is generally faster than using mysql_num_rows.
I'm not sure I understand the logic, aren't you printing "no"; die() when there IS a row found, instead of when now row is found? Either way, here's how I would check:
function four_zero_four($name){
$four_zero_four = mysql_query("SELECT * FROM pages WHERE name = '$name'");
if (mysql_num_rows($four_zero_four) == 0) {
// ROW DOES NOT EXIST
} else {
// ROW EXISTS
}
};
Your code does not work because it wont even be executed if there is no row returned by your query.
Use mysql_num_rows() instead:
$count = mysql_num_rows($four_zero_four);
if($count <= 0){
die("no rows in this table!");
}
Also, you should maybe consider to use MYSQLi commands instead of the old mysql_query() implementation and SELECT *, as they are deprecated.
I have a query that returns a few rows, and I have the following lines of code to retrieve them:
$result_set = mysql_query($query);
while($net_biz_sub_data[]=
mysql_fetch_array($result_set,MYSQL_ASSOC));
My question is what is the right way to retrieve that db query data without getting the last array empty ?
When I count() it is always num of rows + 1, and I would like to correct that.
Because of the way the while loop works, you should do
while($dataz = mysql_fetch_assoc($result_set))
{
$net_biz_sub_data[] = $dataz;
}
Use
$result_set = mysql_query($query);
while($net_biz_sub_data = mysql_fetch_assoc($result_set)){
//use $net_biz_sub_data here
}
I'm trying to debug a MySQL query, and I have trouble understanding why one while loop in my script is not working:
// select db
mysql_select_db($dbname);
for ( $x = $latRange[0]; $x <= $latRange[1]; $x++ )
{
for ( $y = $lngRange[0]; $y <= $lngRange[1]; $y++)
{
$sql="SELECT * FROM $usertable WHERE $xlookup = $x AND $ylookup = $y";
$SQLresult = mysql_query($sql);
while( $row = mysql_fetch_array($SQLresult) )
{
$tmpResult = $row[$popDen];
$result += $tmpResult;
}
}
}
Sample values of the variables described are:
$latRange = array(3,7);
$lngRange = array(9,25);
$popDen = 'ColumnNameIWant'
$xlookup = 'Col1'
$xlookup = 'Col2'
The logic behind my query is that it finds all combinations of x and y, gets the corresponding $popDen value, and adds it to $result. Result is defined at the start of my script, and returned by the program after this loop.
I know that the problem section is my while loop, but I don't quite understand how to fix it as I don't fully understand how mysql_fetch_array functions. I've also tried mysql_fetch_row and my query does not work with this either.
I know from commenting out various chunks of the code, and passing back other numbers that everything else works; it is just this chunk that is failing.
Are there any obvious errors that I am making?
If popDen is a column in your table, you need to get it with:
$tmpResult = $row['popDen'];
and if it is the only value you need, you can simplify / speed up your sql query:
$sql="SELECT `popDen` FROM $usertable WHERE $xlookup = $i AND $ylookup = $y";
Edit: By the way, you might want to initialize your $result variable so that it has a defined / valid / known value if no rows are found.
One obvious error is to use dynamic table names.
This leaves hard to close SQL-injection holes:
Use this code to plug that hole, because mysql-real_escape_string() will not help!
$allowed_tables = array('table1', 'table2');
$clas = $_POST['clas'];
if (in_array($clas, $allowed_tables)) {
$query = "SELECT * FROM `$clas`";
}
See here for more info: How to prevent SQL injection with dynamic tablenames?
And don't forget to always enclose dynamic tablenames in backticks ` or your code will break if you happen to use a reserved word or a number for a table or column name.
I'm using PHP ADOdb and I can get the result set:
$result = &$db->Execute($query);
How do I get the field names from that one row and loop through it?
(I'm using access database if that matters.)
It will depend on your fetch mode - if you setFetchMode to ADODB_FETCH_NUM (probably the default) each row contains a flat array of columns. If you setFetchMode to ADODB_FETCH_ASSOC you get an associative array where you can access each value by a key. The following is taken from ADODB documentation - http://phplens.com/lens/adodb/docs-adodb.htm#ex1
$db->SetFetchMode(ADODB_FETCH_NUM);
$rs1 = $db->Execute('select * from table');
$db->SetFetchMode(ADODB_FETCH_ASSOC);
$rs2 = $db->Execute('select * from table');
print_r($rs1->fields); # shows array([0]=>'v0',[1] =>'v1')
print_r($rs2->fields); # shows array(['col1']=>'v0',['col2'] =>'v1')
To loop through a set of results:
$result = &$db->Execute($query);
foreach ($result as $row) {
print_r($row);
}
Small improvement to the solution posted by #thetaiko.
If you are ONLY needing the field names, append LIMIT 1 to the end of your select statement (as shown below). This will tell the server to send you a single row with column names, rather than sending you the entire table.
SELECT * FROM table LIMIT 1;
I'm working with a table that contains 9.1M records, so this minor change speeds up the query significantly!
This is a function I use to return a field array - I've stripped out some extra stuff that, for example, allows it to work with other DBs than MySQL.
function getFieldNames($strTable, $cn) {
$aRet = array();
# Get Field Names:
$lngCountFields = 0;
$strSQL = "SELECT * FROM $strTable LIMIT 1;";
$rs = $cn->Execute($strSQL)
or die("Error in query: \n$strSQL\n" . $cn->ErrorMsg());
if (!$rs->EOF) {
for ($i = 0; $i < $rs->FieldCount(); $i++) {
$fld = $rs->FetchField($i);
$aRet[$lngCountFields] = $fld->name;
$lngCountFields++;
}
}
$rs->Close();
$rs = null;
return $aRet;
}
Edit: just to point out that, as I say, I've stripped out some extra stuff, and the EOF check is therefore no longer necessary in the above, reduced version.
I initally tried to use MetaColumnNames, but it gave differing results in VisualPHPUnit and actual site, while running from the same server, so eventually
I ended up doing something like this:
$sql = "select column_name, column_key, column_default, data_type, table_name, table_schema from information_schema.columns";
$sql .= ' where table_name="'.$table.'" and table_schema="'.$database_name.'"';
$result = $conn->Execute($sql);
while($row = $result->fetchRow()) {
$out[] = strToUpper($row['column_name']);
}
I think it should work with mysql, mssql and postgres.
The benefit of doing it like this, is that you can get the column names, even if a query from a table returns an empty set.
If you need the Coloumn names even for empty tables or for joins about multiple tables use this:
$db->Execute("SELECT .......");
// FieldTypesArray - Reads ColoumnInfo from Result, even for Joins
$colInfo = $res->FieldTypesArray();
$colNames = array();
foreach($colInfo as $info) $colNames[] = $info->name;
The OP is asking for a list of fieldnames that would result of executing an sql statement stored in $query.
Using $result->fetchRow(), even with fetch mode set to associative, will return nothing if no records match the criteria set by $query. The $result->fields array would also be empty and would give no information for getting the fieldnames list.
Actually, we don't know what's inside the $query statement. Besides, setting limit to 1 may not compatible with all database drivers supported by PHP ADOdb.
Answer by Radon8472 is the right one, but the correct code could be:
$result = $db->Execute($query);
// FieldTypesArray - an array of ADOFieldObject Objects
// read from $result, even for empty sets or when
// using * as field list.
$colInfo = [];
if (is_subclass_of($result, 'ADORecordSet')){
foreach ($result->FieldTypesArray() as $info) {
$colInfo[] = $info->name;
}
}
I have the habit of checking the class name of $result, for as PHP ADOdb will return false if execution fails.