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
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'm working on this project and I need help with something. I am trying to check if someone is already in the database upon logging in and if they are not, they will be added. However, my code always adds them to the database...
Login code:
<?php
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE '$emaillogin' = `emailadress`
AND '$passwordlogin' = `password` LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
echo "E-mail or password incorrect! <br>";
}else{
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
header("location:home.php");
die();
}
}
?>
The function in functions.php:
function check_firstest($accnr){
$query = mysql_query("SELECT count(*) AS 'num' FROM `VRIENDEN` WHERE `accnr` = '$accnr' AND `vriendnr` = '$accnr'");
if($result > 0){
return true;
}
else{
return false;
}
}
The login on its own works just fine, so thats no problem.
Thank you!
Your first query is somewhat odd and you do not capture the values from $_POST into the variables that you are using in the query either
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST["emaillogin"]) and isset($_POST["passwordlogin"])){
$sql = "SELECT `accnr`
FROM `Account`
WHERE `emailadress` = '{$_POST['emaillogin']}'
AND `password` = '{$_POST['passwordlogin']}'
LIMIT 1";
$result = mysql_query($sql);
if ($result == false){
// something went REALLY WRONG, report it
echo mysql_error();
exit;
}
if ( mysql_num_rows($result) == 1 ) {
// found user and password matches
header("location:home.php");
exit;
}else{
// new user, create the account
$accnr = mysql_fetch_array($result);
setcookie("accnr", $accnr[0] , time() + (1800), "/");
$accnmr = $accnr[0];
if(check_firstest($accnmr) == false){
$query = "INSERT INTO `VRIENDEN`
(`accnr`,`vriendnr`)
VALUES ('$accnmr','$accnmr')";
$result = mysql_query($query);
}
// and go to home page
header("location:home.php");
die();
}
}
?>
And of course the fix for the check_firstest() is also required
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
But I have to add
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared parameterized statements
And
You should not be using the mysql_ database extension, it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
You have to count the resulting rows:
function check_firstest($accnr){
$result = mysql_query("SELECT count(*) AS 'num'
FROM `VRIENDEN`
WHERE `accnr` = '$accnr'
AND `vriendnr` = '$accnr'");
if(mysql_fetch_field($result, 0) > 0){
return true;
} else{
return false;
}
}
Here the mysql_num_rows() function gives the number of rows in the result set. If it is greater than 0 then it means that there is some data.
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 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 ?
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.