The title says it all. I have the below code:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
return $result;
}
Seems like it should be the easiest function ever, but the result always returns 8.
Any ideas?
Thanks,
Josh
Your function returns a mysql_query() function result, which is NOT the results of your SQL query.
You have to do something like mysql_fetch_assoc() with the mysql_* old PHP functions.
PS: You should use PDO now, mysql_* are deprecated, it's just a tip ;)
To get number of records in your result
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_assoc($result);
return $row['count'];
}
Also. as previous responder pointed out, you need to stop using mysql_* funcitons and start using either mysqli_* or PDO. PHP Docs for PDO
mysql_query returns a resource: http://php.net/manual/en/function.mysql-query.php
Returning that value won't give you the result of the query. You need mysql_fetch_array().
A working example:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
if($row = mysql_fetch_row($result)) {
return $row[0];
}
else {
return false;
}
}
try to get result using mysql_fetch_array() mysql_fetch_assoc() or mysql_fetch_object()
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_array($result);
return $row['count'];
}
I hope it will help
you need to fetch your query , not return the mysql_query.
try this
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) as counts FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
$row =mysql_fetch_array($result) ;
return $row['counts'];
}
You would be better using mysql_num_rows as it does not need to fetch any data and is more efficient
public function getRows($table) {
$result = mysql_query("SELECT * FROM `".$table."`");
if (! $result) {
// throw exception
}
$rows = mysql_num_rows($result);
return $rows;
}
Related
These lines are from a php function on a web server, the client is an ios app,
I get an error on the result2 query
$result = query("SELECT field1 FROM table1 WHERE field2='%s' limit 1", $value);
$row = mysql_fetch_array($result);
$result2 = query("SELECT field2 FROM table1 WHERE field3='%s' limit 1", $row['field1']);
on Xcode I get the error (in json):
{
error = "The operation couldn't be completed. (Cocoa error 3840.)";
}
here is the definition of the function query
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
what's wrong with that query?
thanks
You are using mysqli_ functions in your query() function yet you are trying to use mysql_fetch_array() to get the results. You need to use: mysqli_fetch_array()
http://www.php.net/manual/en/mysqli-result.fetch-array.php
Actually it looks like your query() function does it for you. You shouldn't need to use a function at all. Look at this section of your query() function:
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
However not sure why it says it is json cause it is just a normal array not a json array. So you should just use this in your code:
$row = $result['result'][0];
This will get the first row.
maybe you have to json_encode the result?
//return json
return json_encode(array('result'=>$rows));
So I have a function to gather user_data in PHP & MYSQL, and the thing is that I want to upgrade MYSQL in MYSQLi.
The MYSQL code is following:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM members where id = $id"));
The MYSQLi code I tried but with no use:
$data = $db_connect->query("SELECT $fields FROM ´members´ where id = $id");
and
$result = $db_connect->query("SELECT $fields FROM ´members´ where id = $id");
$data = $result->fetch_assoc();
I don't know what could be wrong, in the 1:st example I have no errors but the data isn't displaying, and in the 2:nd code I noticed I need the fetch_assoc function to make it work, but here I get the errors saying
Call to a member function fetch_assoc() on a non-object
Seems like you have an error in your query. MySQli->query() will return FALSE on failure.
[UPDATE 2] Try this code:
$result = $db_connect->query("SELECT $fields FROM members where id = $id");
if (!$result) {
printf("Errormessage: %s\n", $db_connect->error);
}
else {
while ($data = $result->fetch_assoc()) {
print_r ($data);
}
}
I'm 'doomsday' (mysql_ depreciation!) prepping some of my older applications that take the use of mysql_ extentions. I am currently converting them into PDO.
I use a lot of functions to make my work easy. However I cant get the $db->query within a function to work. For example I'm converting this function:
function GetAccount($account_id){
$Query = mysql_query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (mysql_num_rows($Query) > 0){
$Result = mysql_fetch_assoc($Query);
return $Result;
} else {
return false;
}
}
Into this PDO function.
function GetAccount($account_id){
global $db;
$Result = $db->query("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
I have established a PDO connection outside of this function, which works fine with queries outside of any function.
The problem for the second (PDO) function is that the $Result is empty. A var_dump returs: bool (false).
What am I forgetting/doing wrong?
Thank you :)
Fixed it, new function:
function GetAccount($account_id){
global $db;
$Result = $db->prepare("SELECT name, balance, account_number FROM accounts WHERE id = '$account_id'");
$Result->execute();
$Result = $Result->fetch();
if (count($Result) > 0){
return $Result;
} else {
return false;
}
}
The only thing I did was :
$Result->prepare("query stuff");
$Result->execute();
$Result = $Result->fetch();
I've been trying to get a series of nested loops working to select the database name from one table then query the selected table in that database, and add up the results and display the number of them and the database name.
I have gotten the code to work but it keeps displaying:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in
I have tried every way possible I have found online to help, but none work.
$resulta = mysql_query("SELECT dbname AF012 FROM Customer");
while($data = mysql_fetch_array($resulta))
{
$db = $data[' dbname '];
$result = null;
$result2 = mysql_query("SELECT changemade FROM $db.orders");
//looping through the results
while($row = mysql_fetch_array($result2))
{
//checking if any record is 1,2 or 3
if( ($row[‘changemade’]== 1) || ($row[‘changemade’]== 2) || ($row[‘changemade’]== 3) ) {
//if any match the if adding 1 to the counter
$counter ++;
}
}
unset($result2);
echo $db." ".$counter;
echo "<br>";
$counter = 0;
$result = null;
$result2 = null;
}
All the database connections are made and work fine, so it has nothing to do with that. Any help would be great.
You need to introduce error handling, also you can streamline your code. The current point of failure is querying the database and fetching from it, so you can encapsulate it into a function of it's own which will also reduce your code:
function mysql_query_array($query)
{
if (!$result = mysql_query($query)) {
throw new Exception(sprintf('Invalid query "%s", error: %s.', $query, mysql_error()));
}
return function () use ($result) {
return mysql_fetch_array($result);
};
}
With that little helper function, your code is now more compact and it has actual error handling:
$queryA = mysql_query_array("SELECT dbname AF012 FROM Customer");
while ($data = $queryA())
{
$counter = 0;
$queryB = mysql_query_array("SELECT changemade FROM {$data['dbname']}.orders");
while ($row = $queryB())
{
if (in_array($row['changemade'], range(1, 3))) {
$counter++;
}
}
printf("%s %s<br>\n", $db, $counter);
}
This is caused by the fact that mysql_query return false if the query fails, so one of your query fails and mysql_fetch_array() gets a boolean. Try changing $db = $data[' dbname ']; to $db = $data['dbname'];
$qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
$aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");
function vraagOp($table,$where)
{
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
$aVraagOp = mysql_fetch_assoc( $rVraagOp );
return $aVraagOp;
}
only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
echo "testing <br>";
}
It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
Is this possible?
This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
static $rVraagOp;
if(!$rVraagOp){
$qVraagOp = "SELECT * FROM $table WHERE $where";
$rVraagOp = mysql_query( $qVraagOp );
}
return mysql_fetch_assoc( $rVraagOp );
}
That should do what you're after.
This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
$sql= "SELECT * FROM $table WHERE $where";
$query= mysql_query($sql);
if ($query != false)
{
$result = array();
while ( $row = mysql_fetch_assoc($query) )
$result[] = $row;
return $result;
}
return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
foreach ($rows as $row)
use($row);
}
This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call. It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
// Holds our mysql resources in a map of "{$table}_{$where}" => resource
static $results = array();
$key = $table . '_' . $where;
if (!isset($results[$key]))
{
// first call of this particular table/where
$results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
}
$row = mysql_fetch_assoc($results[$key]);
if ($row === false)
// remove this key so a subsequent call will start over with a new query
unset($results[$key]);
return $row;
}
// Usage
while ($row = vraagOp("table1", "where field > 7")) {
print_r($row);
}
This
while (vraagOp("testtable","testtype = test"))
{
echo "testing <br>";
}
will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?
You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.
Your example won’t work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn’t.
How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";
$result_gpfsF=mysql_query($sql_gpfsF);
while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{
call_function();
}
function call_function()
{
echo " Function Called </ br>";
}