mysql_num_fields(): supplied argument is not a valid MySQL result resource - php

I'm working on a custom CMS, made changes to the DB schema and presentation layer. I'm getting an error relative to mysql_num_fields and mysql_num_rows using the following section of code. Can someone give me an idea of why these errors are being raised?
public function viewTableData($db_name,$table_name,$fld01,$where_clause,$order_by,$asc_desc){
mysql_select_db($db_name);
if($fld01!="")
{
$sql = "Select $fld01 from $table_name";
}
else
{
$sql = "Select * from $table_name";
}
if($where_clause!="")
{
$sql=$sql." ".$where_clause;
}
if(($order_by!="")&&($asc_desc!=""))
{
$sql=$sql." ".$order_by." ".$asc_desc;
}
else if(($order_by!="")&&($asc_desc==""))
{
$sql=$sql." ".$order_by;
}
//return "<br/>sql :".$sql;
$result = mysql_query($sql);
$count_fields = mysql_num_fields($result);
$count_rows = mysql_num_rows($result);
if($count_rows>0)
{
$index = 0;
unset($this->data_array);
while ($row = mysql_fetch_assoc($result)) {
$this->data_array[] = $row;
} // while
//Finally we release the database resource and return the multi-dimensional array containing all the data.
mysql_free_result($result);
return $this->data_array;
}
}

Slap an echo mysql_error(); line after the mysql_query line to see the error from the server.

You don't test $result, which can be FALSE upon return from mysql_query()
Also, I would rewrite:
if($order_by!="")
{
$sql.=" ".$order_by." ".$asc_desc;
}
MySQL doesn't care about extra spaces here and there.

Related

MYSQLI multi query function

I want to create a function that automatically makes a connection to the database and performs the given queries but I can't get it to work and it gives no errors.
I think I'm not outputting in the correct way my goal is to output a array that stores all the returned values from the queries.
Here is my code so far hope you can help:
public function db_query() {
$ini = parse_ini_file($_SERVER['DOCUMENT_ROOT'] . '/app.ini');
$mysqli = new mysqli($ini['db_location'], $ini['db_user'], $ini['db_password'], $ini['db_name']);
// create string of queries separated by ;
$query = "SELECT name FROM mailbox;";
$query .= "SELECT port FROM mailbox";
// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);
if ($result) {
do {
// grab the result of the next query
if (($result = mysqli_store_result($mysqli, 0)) === false && mysqli_error($mysqli) != '') {
echo "Query failed: " . mysqli_error($mysqli);
while ($row = $result->fetch_row()) {
echo $row[0];
}
}
} while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
echo "First query failed..." . mysqli_error($mysqli);
}
}
Note: I did not add the parameter for the query just for testing
purposes.
public function db_query($mysqli) {
$return = [];
$result = mysqli_query($mysqli, "SELECT name FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
$result = mysqli_query($mysqli, "SELECT port FROM mailbox");
while ($row = $result->fetch_row()) {
$return[] = $row[0];
}
return $return;
}
simple, clean, efficient, always works

Looping through a MySQL query in PHP

I have some code that queries my MySQL database. My problem is, if checks only the first row of my table. I know I need to have a for loop, but what I tried out does not work. The working code that checks only the first line is
public function checkPart($aid, $uname) {
$result = mysql_query("SELECT * FROM part WHERE aid = '$aid'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$aiddb = $result['aid'];
$unamedb = $result['uname'];
if ($unamedb == $uname) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return mysql_error();
}
}
What I tried is this:
public function checkPart($aid, $uname) {
$result = mysql_query("SELECT * FROM part WHERE aid = '$aid'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
for($x=1; $x<= $no_of_rows;$x++){
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$aiddb = $result['aid'];
$unamedb = $result['uname'];
if ($unamedb == $uname) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return mysql_error();
}
}
}
Can someone please help me with correcting my code? I am a beginner so pardon me if the question is too simple.
The de facto way to do this is with a while loop:
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows == 0) {
return mysql_error();
} else {
while ($row = mysql_fetch_assoc($result)) {
// ... use $row['aid'], $row['uname'], etc.
}
}
Your own code may work, but you were overwriting $result:
$result = mysql_fetch_array($result);
So, after one iteration of the loop, you had lost the result of the query.
Note: mysql_* functions are deprecated due to security issues, you are advised to learn mysqli_* or PDO instead.
public function checkPart($aid, $uname)
{
// It's think it's better to distinct the query itself
// Therefore u can re-use the code easily.
$sql = "SELECT * FROM part WHERE aid = \"$aid\"";
$result = mysql_query($sql);
// Catch errors
if (!$result)
{
die('Invalid query: ' . mysql_error());
}
// If i'm correct u're using for just to loop the result
// of fetch_array
// It's easier like in the example in the man to do
while ($row = mysql_fetch_array($result))
{
// Didn't see where this variable is used but u'll use later i suppose
$aiddb = $row['aid'];
$unamedb = $row['uname'];
if ($unamedb == $uname)
{
// user authentication details are correct
return $result;
}
else
echo 'User not found \n';
}
} // checkPart()
I'm pretty new to coding aswell but I suggest u to read the man a lot. It's really Helped me. Btw u should take a look at PDO for database query.
Source :
PHP.net fetch_array
PDO introduction

MySQL query returning false

I am using XAMPP server. Using phpMyAdmin, I created a database and a table named "Users". When I run the code below, it says Error in your query. Whats wrong with my code?
function selectMultiRows($query)
{
if((#$result = mysql_query ($query))==FALSE)
{
echo "<strong>Error in your query:</strong> <br>$query";
}
else
{
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($result))
{
$data[$count] = $row;
$count++;
}
return $data;
}
}
$query = "select * from Users";
$returnedData = selectMultiRows($query);
$totalRecords = count($returnedData);
for($i=0;$i<$totalRecords;$i++)
{
echo $returnedData[$i]["username"] . "<br>";
}

What's wrong with this sql query and mysql_fetch_array?

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));

How to echo an array multiple times in one page?

I was wondering if someone could help me with this problem.
I want to print/echo the solution of the function multiple times on the same page. Is that possible?
Here's my function:
public function getFeedback($p_iUserid) {
include("Connection.php"); //open db
try
{
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return $rResult;
}
catch(Exception $e)
{
// no connection database
$feedback = $e->getMessage();
}
mysqli_close($link);
}
And this is how I manage to call on the function by now. But it only works once:
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($allUsers))
{
echo $oUser['DiaryOpmerkingen'];
}
}
I hope someone can help!
Thanks anyway.
Create a function for your printing task, then call it as many times as you want:
function print_the_stuff($feedbackPatient){
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($allUsers))
{
echo $oUser['DiaryOpmerkingen'];
}
}
}
Then, wherever you need to print:
print_the_stuff($feedbackPatient);
The easiest way to do this is probably to get the whole result set in one go, and then pass that around.
This might be costly in terms of performance if the result set is large, but it's probably not going to make a significant difference. It is particularly easy with the mySqli extension, because you can use mysql_fetch_all.
public function getFeedback($p_iUserid) {
include("Connection.php"); //open db
try
{
$sql = "select DiaryOpmerkingen, DiaryDoctorcomment from tblDiary
WHERE fk_UserId = ".$p_iUserid."
AND DiaryDay = '".$this->Day."';";
$rResult = mysqli_query($link, $sql);
return mysqli_fetch_all($rResult, MYSQLI_ASSOC);
}
catch(Exception $e)
{
// no connection database
$feedback = $e->getMessage();
}
mysqli_close($link);
}
You would then get an associative array returned from getFeedback, and could loop through this as normal:
$feedback = getFeedback($id);
foreach ($feedback as $item) {
echo $item['DiaryOpmerkingen'];
}
I think it should be :
$feedbackPatient = getFeedback($p_iUserid);
if(mysqli_num_rows($feedbackPatient) > 0)
{
while($oUser = mysqli_fetch_assoc($feedbackPatient))
{
echo $oUser['DiaryOpmerkingen'];
}
}
why are u using diff result for mysqli_num_rows and sqli_fetch_assoc ?

Categories