Table: student
student.php
<?php
function findStudentRecord()
{
//Db connection
$q1 = "select * from student where gender = 'F'";
$r1 = mysqli_query($dbc, $q1);
$total_records = mysqli_num_rows($r1);
$record = array();
if($total_records > 0)
{
while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
{
$record[] = $row1;
}
}
else
{
//[HERE]
}
return $record;
}
$record = findStudentRecord();
//[HERE]
?>
I want to find female student record but there is no record from my database. How do I return 0 value from function and display "No record found" on my web page in [HERE] section?
if($total_records > 0)
add no else block so it will return an empty array now you can do something like this
$records = findStudentRecord();
if(count($records) === 0) {
echo "No record found";
}
I would not change your function. It returns an array (may be empty) in any case wich is quite consistent.
Instead look at the number of array items returned:
$record = findStudentRecord();
//[HERE]
if(count($record) == 0) {
echo "No record found";
} else {
// what ever
}
Related
So I've got a dropdown that has a list of customers that you can select from. It uses a function (that someone else built) which works fine when there are 2 or more customers but dies when there it only one. When there's one customer, each item in the dropdown is the first character of each column for that one customer.
Here is the function:
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if ($check ==1)
{
$row = mysqli_fetch_assoc($run);
return($row);
}
elseif($check >1)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I'm fairly certain that it's the ($check == 1) stuff but I can't work out the best way to re-do all of that to make it work without causing other errors (specifically "cannot modify header")
This is what's called up on the page with the dropdown:
$customers = getCustomerBy('users_user_id',$user['user_id']);
Also, here is the code for the dropdown:
<?
foreach ($customers as $customer)
{
$selected = '';
if (isset($gig['customers_customer_id']) && $customer['customer_id'] == $gig['customers_customer_id'])
{
$selected = ' selected ';
}
echo "\t<option value=\"".$customer['customer_id']."\" $selected>".$customer['customer_company_name']."</option>";
}
?>
The code that builds the dropdown is expecting an array of arrays, but instead when it's a single row you're passing it an array of strings. Treat both cases ($check > 0) the same.
function getCustomerBy($column = "",$value = "")
{
global $conn;
if ($value == '')
{
return(null);
}
$sel = "SELECT
customers.*,
customerStatus.code customerStatus
FROM customers,
customerStatus
WHERE customer_id
and customerStatus.id = customers.customerStatus_id and ". mysqli_real_escape_string($conn,$column) ."='". mysqli_real_escape_string($conn,$value) ."'";
// error_log($sel);
$run = mysqli_query($conn, $sel);
$check = mysqli_num_rows($run);
if($check > 0)
{
$rows = array();
while ($row = mysqli_fetch_assoc($run))
{
$rows[] = $row;
}
return($rows);
}
else
{
return(null);
}
}
I assume there's copy/paste errors in your query because it doesn't look right.
I don't know how the returning array is used by the rest of your code but you can try the following:
Change:
if ($check ==1) {
$row = mysqli_fetch_assoc($run);
return($row);
}
To this:
if ($check == 1) {
$rows = array();
$rows[] = mysqli_fetch_assoc($run);
return($rows);
}
I have some php that gets data from the database, and I just want to get it into my view. I had this code from earlier where I just wanted 1 row, however now I want to get all the data into the view.
Do I have to make a loop and get each row into a string and keep appending to it?
here's the php:
if ($result = $mysqli->query("SELECT * FROM myData")) {
$row_cnt = $result->num_rows;
if ($row_cnt > 0) {
$row = $result->fetch_assoc();
$data = $row["data"];
echo $data;
} else {
echo "no data";
}
/* close result set */
$result->close();
}
Something like this should do it, unless you need it in the code later. If that is the case store it to an array.
while($row = $result->fetch_assoc()) {
echo $row["data"];
//$array[] = $row["data"];
}
Try this way :
if ($result = $mysqli->query("SELECT * FROM myData")) {
$row_cnt = $result->num_rows;
if ($row_cnt > 0) {
While ($row = $result->fetch_assoc()) {
$data .= $row["data"]."<br>";
}
echo $data;
} else {
echo "no data";
}
/* close result set */
$result->close();
}
Here is my function in DB_Functions.php, i want to get two different values from two different tables in single function only here is the code what i have tried so far but the values are coming null.
public function getUserMetvalue($exname,$fname) {
$result = mysql_query("SELECT metvalue FROM fitnessactivitylist WHERE activityname='$exname'") or die(mysql_error());
$result1 = mysql_query("SELECT weight FROM users WHERE name='$fname'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
$no_of_rowss = mysql_num_rows($result1);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
if ($no_of_rowss > 0) {
$result1 = mysql_fetch_array($result1);
return $result1;
}
return $result;
} else {
//exercise name not found
return false;
}
}
here is my index.php
//TAG METVALUE
if ($tag == 'metvalue') {
$exname = $_POST['exname'];
$fname = $_POST['fname'];
$usermetvalue = $db->getUserMetvalue($exname,$fname);
if ($usermetvalue != false) {
$response["success"] = 1;
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
echo json_encode($response);
}
else {
$response["error"] = 1;
$response["error_msg"] = "No exercise found!";
echo json_encode($response);
}
}
Spot the differences:
$result = mysql_query("SELECT metvalue etc...
^^^^^^^^
$result1 = mysql_query("SELECT weight etc...
^^^^^^
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
^^^^^^
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
^^^^^
You fetch fields which aren't used later, then attempt to access fields which weren't fetched in the first place...
function a_function() {
$a = 'Learn';
$b = 'Programming.';
return array($a, $b);
}
list($one, $two) = a_function();
echo $one . ' ' . $two;
I have read several of these posts on the site, but still can't find the answer to my problems. I have a while loop where for every entry in the database the table populates. Although if the table in the database is empty, I want it to display a messaged instead. Any ideas of what is wrong here? (aware of the deprecated tags)
$result = mysql_query("SELECT * FROM blog");
while($row = mysql_fetch_array($result))
{
if(count($row) === 0)
{
echo 'No Data';
}
<table code>
}
Use mysql_num_rows for counting rows from DB.
<?php
if (mysql_num_rows($result) > 0) {
echo '<table>';
while ($row = mysql_fetch_assoc($result)) {
echo '<tr>...</tr>';
}
echo '</table>';
} else {
echo 'No result found';
}
?>
EDIT: updated code for table.
$result = mysql_query("SELECT * FROM blog");
if(mysql_num_rows($result) === 0) {
echo 'No Data';
} else {
while($row = mysql_fetch_array($result)) {
// code
}
}
use mysql_num_rows() to get count of query result rows
$rows = mysql_num_rows($result);
if($rows > 0) {
// do your stuff
}
Use mysql_num_rows for counting number of rows are returned in query.
Try this. mysql_num_rows will check the records in database. On true condition it will allow to execute the while loop other wise else condition will execute.
$result = mysql_query("SELECT * FROM blog");
if(mysql_num_rows($result) > 0) {
echo 'No Result Found';
} else {
while($row = mysql_fetch_array($result)) {
// Here your Data
}
}
If you want to display when no record found then
$result = mysql_query("SELECT * FROM blog");
while($row = mysql_fetch_array($result))
{
if(count($row) == 0 || count($row) < 1)
{
echo 'No Data';
}
else
{
//print records
}
}
My code looks like this:
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
Problem is that when there is no row to select, nothing happens, my $row array is empty.
How can i have this present a message of "no row found" when no rows match the select?
try
if (mysql_num_rows($result) == 0) {
// Show message
} else {
// do your while stuff here
}
Use mysql_num_rows() to determine the amount of rows in your result.
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
if(mysql_num_rows($result) == 0) {
echo "No row found!"
} else {
while($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
}
}
if (mysql_num_rows($result) == 0) {
echo "Result is empty!";
}
You should've read the description of mysql_query, it gives you the answer: http://php.net/mysql_query
mysql_num_rows() only works on buffered queries. If you have potentially a large/huge result set you might switch to unbuffered queries and num_rows is not an option anymore.
You can test the return value of the first call to mysql_fetch_array(). If it's FALSE there were no matching records.
<?php
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo '0 rows';
}
else {
do {
echo htmlspecialchars($row['x']), "<br />\n";
} while($row=mysql_fetch_array($result, MYSQL_ASSOC));
}
The downside of this do { } while() is that the $row=mysql_fetch... code has been duplicated. But it's only a small doublet.
This method never seems to fail for me.
if(!$result = mysqli_query($con,"SELECT * FROM `picdb` WHERE `picid` = '$picid' ")){
// Enter you error message here.
} else {
// Do all your magic.
}