Check for a null value from a database -- failing - php

I am retrieving 3 fields from a database, and by default, only the username field will have content. The other information will be added in from a user application. I want to show the field as "No Info" if there is no entry in the field. I am trying to use both empty() and is_null() to no avail. A var_dump of $row['firstname'] and $row['lastname'] returns NULL in both cases.
<?php
if (isset($_GET["subcat"]))
$subcat = $_GET["subcat"];
if (isset($_GET["searchstring"])) {
$searchstring = $_GET["searchstring"];
}
$con = mysqli_connect("localhost","user","password", "database");
if (!$con) {
echo "Can't connect to MySQL Server. Errorcode: %s\n". mysqli_connect_error();
exit;
}
$table = 'USERS';
$brand = '%' . $searchstring . '%';
$rows = getRowsByArticleSearch($brand, $table);
echo "<table border='0' width='100%'><tr>" . "\n";
echo "<td width='15%'>Username</td>" . "\n";
echo "<td width='15%'>Firstname</td>" . "\n";
echo "<td width='15%'>Surname</td>" . "\n";
echo "</tr>\n";
foreach ($rows as $row) {
if (is_null($row['firstname']) || $row['firstname'] == "") {
$row['firstname'] == "No Info";
}
if ($row['lastname'] == null || $row['lastname'] == "") {
$row['firstname'] == "No Info";
}
var_dump($row['firstname']);
var_dump($row['lastname']);
echo '<tr>' . "\n";
echo '<td>'.$row['username'].'</td>' . "\n";
echo '<td>'.$row['firstname'].'</td>' . "\n";
echo '<td>'.$row['lastname'].'</td>' . "\n";
echo '</tr>' . "\n";
}
echo "</table>\n";
function getRowsByArticleSearch($searchString, $table) {
$con = mysqli_connect("localhost","user","password", "database");
$recordsQuery = "SELECT username, firstname, lastname FROM $table WHERE lower(username) LIKE ? ";
if ($getRecords = $con->prepare($recordsQuery)) {
$getRecords->bind_param("s", $searchString);
$getRecords->execute();
$getRecords->bind_result($username, $firstname, $lastname);
$rows = array();
while ($getRecords->fetch()) {
$row = array(
'username' => $username,
'firstname' => $firstname,
'lastname' => $lastname,
);
$rows[] = $row;
}
return $rows;
} else {
print_r($con->error);
}
}

Turn on display_errors and set error_reporting to E_ALL (either in php.ini or in a htaccess). This should reveal any non-obvious mistakes.
Try the following for checking if something is empty:
<?php
if(!isset($row['...']) || empty($row['...']))
{
$row['firstname'] = 'No Info';
}
?>
Also, please note you're using '==' to set the $row things to 'No Info'. Al this does is return 'true' (or 1). Use a single '=' to set variables.

First and your main issue:
You are using comparison operators in $row['firstname'] == "No Info"; instead of assignement operators $row['firstname'] = "No Info";
Other issues:
Why do you establish the connection twice? Or actually multiple times? Find a way to let your functions know the connection!
Factor the connection out into an include.
Why do you do that while loop, if you can access the returned array directly?

Two things to try...
if($row['field'] === NULL) { }
if(isset($row['field'])) { }

You can check the empty data using is_null property .Refer this link for more details
http://php.net/manual/en/function.is-null.php
is_null($row['field'])
Use
if(is_null($rows['field'])){
// Code Here
}else{
//code here
}

Related

How do I pass this information to print it out in another document? PHP MySQL

I am having trouble echoing row data within the page I want to print it out to.
My function works, but only echoes the information because it is local (within the same function).
I'm trying to get this function to echo the database's information to another .php file (same program).
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
}
}
Here is the part of the other file I need to print the information from the function to:
<?php
if (isset($_SESSION["username"])) {
$eventDAO = new EventDAO($connection);
$event = $eventDAO->findByUsername($_SESSION["username"]);
foreach((array)$event as $e) {
echo $e->getUsername() . ' ' . $e->getDate() . '<br>';
}
}
?>
I'm trying to output the username/date.
Not 100% on this concept.
If you're simply trying to output username/date from one file to another, try using sessions.
public function findByUsername($username) {
$sql = 'SELECT * FROM events WHERE username=? ';
$statement = DatabaseHelper::runQuery($this->connection, $sql, Array($username));
while ($row = $statement->fetch()) {
echo $row['username'] . "<br />";
echo $row['date'] . "<br />";
$_SESSION['getuname'] = $row['username'];
$_SESSION['getdate'] = $row['date'];
}
}
You can then output the information on another php file simply by echoing it out.
echo "Username is ". $_SESSION['getuname'];

all of my php syntax is true,but update query is not working in while loop

This is cancel_order function,that also in it will call the increase_gameamount() function, i am trying to call increament_gameamount() function it works but when I try to call it from while loop nothing changes in database.
//cancel function
function cancel_order($ord) {
global $conn;
$bqty = 0;
$gqty = 0;
$res = array();
echo "entered cancel function " . $ord . "<br>";
$st = "select (B_qty+G_qty) newqt, B_GM_ID from tb_basket b, tb_game g
where b.B_GM_ID = g.G_ID
and B_O_ID='$ord' ";
$sql = $conn->prepare($st);
$sql->execute();
$sql->bind_result($newqt, $gid);
$i = 0;
while($row = $sql->fetch()) {
$res[$i][0] = $newqt;
$res[$i][1] = $gid;
$i++;
}
$j = 0;
$sql->free_result();
$sql->close();
while($j < sizeof($res)) {
echo $gd = $res[$j][0] . "<br>";
echo $qty = $res[$j][1] . "<br>";
increament_gameamount($gd, $qty);
$j++;
}
}
//increament function
function increament_gameamount($gameid, $new_qty) {
global $conn;
echo "entered increament_gameamount function";
echo $gameid;
echo $new_qty;
$varupdateqty = $conn->prepare("update tb_game set G_qty=? where G_ID=?");
$varupdateqty->bind_param("ss", $new_qty, $gameid);
$varupdateqty->execute();
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
As I stated in the comments I think you are failing on the WHERE of your query because
echo $gd=$res[$j][0]."<br>";
is making $gd a string like 125<br> and the DB cannot find that.
Also, this would cause an error but if the type of your column is int and you pass:
echo $qty=$res[$j][1]."<br>";
again you make $qty something like 1000<br> and that would fail again this would be an error the above for ID check would not.
UPDATE
Just realized I did not specifially state the resolution. Set the variables then echo them and you should be all good.
$gd=$res[$j][0];
$qty=$res[$j][1];
echo $gd . "<br>" . $qty . "<br>";

mysqli query returns no results

I am new to mysqli and I am trying to output a simple query into an HTML table.
I get three blank cells returned but nothing inside of them.
I tried looking around here to find this and maybe my search skills aren't up to par, so either nobody else got stuck here, or I can't search for squat!
Anyway, this is my code:
<?php
$mysqli = new mysqli("localhost", "webuser", "mysecretpassword", "userdb");
/* check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
if ( $result = $mysqli->query("select first_name, last_name, last_activity_date from users order by first_name" ) )
{
$finfo = $result->fetch_fields();
foreach ( $finfo as $val )
{
echo "<tr>\n";
echo "<td>$val->first_name</td>\n";
echo "<td>$val->last_name</td>\n";
echo "<td>$val->last_activity_date</td>\n";
echo "</tr>\n";
}
$result->close();
}
$mysqli->close();
?>
While I have seen other examples using printf() I am not familiar with its syntax since I am not used to C style printf since I had used the echo style previously on my old database transactions.
Any help is greatly appreciated here. Thanks!
Try this
foreach ( $finfo as $val )
{
echo "<tr>\n";
echo "<td>" . $val->first_name . "</td>\n";
echo "<td>" . $val->last_name . "</td>\n";
echo "<td>" . $val->last_activity_date . "</td>\n";
echo "</tr>\n";
}
if ( $result = $mysqli->query("select first_name, last_name, last_activity_date from worker order by first_name" ) )
{
while ( $val = $result->fetch_object() )
{
echo "<tr>\n";
echo "<td>" . $val->first_name . "</td>\n";
echo "<td>" . $val->last_name . "</td>\n";
echo "<td>" . $val->last_activity_date . "</td>\n";
echo "</tr>\n";
}
$result->close();
}
It's not about the foreach or while loop, fetch_fields does not return the query result but the meta data about the columns of the query result (such as name, length, type etc)
You should also get a PHP warning as well on $val->first_name since this object member isn't defined.

display data from SQL database into php/ html table [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a database on MySQL and I want to display one of my SQL tables on a HTML or PHP table. I have searched online and cannot implement this feature. Could someone please help me with the coding?
database = 'hrmwaitrose'
username = 'root'
host = 'localhost'
There is no password.
I would like to display the data from the "employee" table.
PHP provides functions for connecting to a MySQL database.
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results
echo "<tr><td>" . htmlspecialchars($row['name']) . "</td><td>" . htmlspecialchars($row['age']) . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
mysql_close(); //Make sure to close out the database connection
In the while loop (which runs every time we encounter a result row), we echo which creates a new table row. I also add a to contain the fields.
This is a very basic template. You see the other answers using mysqli_connect instead of mysql_connect. mysqli stands for mysql improved. It offers a better range of features. You notice it is also a little bit more complex. It depends on what you need.
Please note that "mysql_fetch_array" is now deprecated since PHP 5.5.0, and it was removed in PHP 7.0.0. So please take a look in "mysqli_fetch_array()" instead.
Here's a simple function I wrote to display tabular data without having to input each column name:
(Also, be aware: Nested looping)
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
UPDATED FUNCTION BELOW
Hi Jack,
your function design is fine, but this function always misses the first dataset in the array. I tested that.
Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.
The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.
You can avoid that by moving the if condition above the second foreach loop like this:
function display_data($data) {
$output = "<table>";
foreach($data as $key => $var) {
//$output .= '<tr>';
if($key===0) {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= "<td>" . $col . '</td>';
}
$output .= '</tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
else {
$output .= '<tr>';
foreach($var as $col => $val) {
$output .= '<td>' . $val . '</td>';
}
$output .= '</tr>';
}
}
$output .= '</table>';
echo $output;
}
Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016
and another update that removes redundant code blocks that hurt maintainability of the code.
function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
$output .= '<tr>';
foreach($var as $k => $v) {
if ($key === 0) {
$output .= '<td><strong>' . $k . '</strong></td>';
} else {
$output .= '<td>' . $v . '</td>';
}
}
$output .= '</tr>';
}
$output .= '</table>';
echo $output;
}
refer to http://www.w3schools.com/php/php_mysql_select.asp .
If you are a beginner and want to learn, w3schools is a good place.
<?php
$con=mysqli_connect("localhost","root","YOUR_PHPMYADMIN_PASSWORD","hrmwaitrose");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM employee");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName']; //these are the fields that you have stored in your database table employee
echo "<br />";
}
mysqli_close($con);
?>
You can similarly echo it inside your table
<?php
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['FirstName'] . "</td><td> " . $row['LastName'] . "</td></tr>"; //these are the fields that you have stored in your database table employee
}
echo "</table>";
mysqli_close($con);
?>
Look in the manual http://www.php.net/manual/en/mysqli.query.php
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>

PDO row count confusion

I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}

Categories