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 ?
Related
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
I have a class called Person, with its getters and setters, and I want to know how I can return a List from Data Layer. In C# I use List and I can return the list, but in PHP I don't know how.
function AllPersons()
{
try
{
$objConn = new Connection();
$conn = $objConn ->Connect();
$sql = "SELECT * FROM PERSON";
$answer= mysqli_query($cn, $sql);
if(mysqli_num_rows($answer) > 0)
{
while($row = mysqli_fetch_array($answer))
{
/*here i want to do something like in C#
List<Person>listPerson;
listPerson.add(objPerson);*/
}
}
else
{
return null;
}
}
catch (Exception $e)
{
//FB::log("nada");
}
}
Create an array and fill it.
listPerson = [];
while($row = mysqli_fetch_array($answer)) {
listPerson[] = new Person($row);
}
In PHP arrays replace the use of Lists/Arrays you'd use in .NET.
They're really flexible when it comes down to mutations.
In this case you'd probably approach it like:
...
$persons = array();
while($row = mysqli_fetch_array($answer))
{
// Using [] appends the content of $row to the $persons array.
$persons[] = $row;
}
...
Read more about the flexibility of PHPs arrays here.
List is a dimensionless array in C# (Can also be used in dimensional). The arrays in PHP also dimensionless. So you can use arrays.
...
$listPerson = array();
while($row = mysqli_fetch_array($answer))
{
$listPerson[] = objPerson;
}
...
function AllPersons()
{
try
{
$objConn = new Connection();
$conn = $objConn ->Connect();
$sql = "SELECT * FROM PERSON";
$answer= mysqli_query($cn, $sql);
if(mysqli_num_rows($answer) > 0)
{
while($row = mysqli_fetch_array($answer))
{
print_r($row);
}
}
else
{
return null;
}
}
catch (Exception $e)
{
//FB::log("nada");
}
}
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
In a php function, i tried to insert a row in a database table as
function abnc()
{
$link = conn to db;
$query = "insert into table( a,c ,v) values (1,2,3);"
$result = mysqli_query($link, $query);
if(mysqli_rows_affected($link) == 1){
close conn;
return true;}
else{
return false;
close conn;
}
now, at other place, i called this function, and tried to read the values i had inserted
as
$done = abnc();
if($done)
{
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
echo "true";
echo mysqli_num_rows($result);
}
else
{
echo 'false';
}
the output i get is true0;
I think while the function was executing, the script just continued.
I want it to wait until function execution is finished.
Any solution ??
The script does not continue. When you call abnc() that function will be executed and return a value which you store in the variable $done. This value is presumably true since your output is true0.
In abnc() you insert a row. Which means that one row was affected and the function returns true. And you close the db connection, which might be why you cant access your inserted data later.
try this
$done = abnc();
$link = conn to db;
if ($done) {
$query = "select * from table where a=1 and c=2 and v=3";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
do {
$resultSet = array();
if (($row = mysqli_store_result($link))) {
while ($row = mysqli_fetch_assoc($row)) {
$resultSet[] = $row;
}
$return[] = $resultSet;
#mysqli_free_result($row);
}
} while (#mysqli_next_result($link));
return $return;
}
} else {
return false;
}
You closed the database connection in your function try opening it outside the function and closing at the end of your script.
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.