PDO - Test Of Empty Results - php

I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.

// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}

I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}

After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.

Related

How to create search boxes to spit out the results from a database

I am creating a result page using php to pull data from database.
I have been able to connect the database to my webspace and displayed the data.
Now , I would like to have the page not show all the data at once. I want to add an input field example "Origen= Los Angeles" "Destination = London" and then show the results based on that criteria.
This is my first time doing something like this so if this sounds like I should know this I'm sorry. I hope I can get some help.
<?php
// include connection settings
require_once "connect.php";
// display a list of flights
if(!empty($_GET) && !empty($_GET['name'])){
$query = "SELECT * FROM Flight_Information WHERE name LIKE ''".
$_GET['name']."".$_GET['name']."'";
} else {
$query = "SELECT ID, airlineName, departureAirport, departureDate, destinationAirport FROM Flight_Information";
} // END if
$result = $db->query($query);
if ($result) {
// ... display results in while loop
while ($row = $result->fetch_assoc()) {
echo '<li>'.$row['airlineName'].' '.$row['departureAirport'].''.$row['departureDate'].''.$row['destinationAirport'].'</li>';
} // END while
} else {
// if there was an error with your query
// this will display it
echo "SQL Error: " . $db->error;
} // END if
?>
</ul>
<?php
if (!empty($_GET) && !empty($_GET['Flight_Information_ID'])) {
$Flight_Information_ID = $_GET['Flight_Information_ID'];
$query = "SELECT * FROM Flight_Information WHERE ID =" . $Flight_Information_ID;
// perform the query
if ($result = $db->query($query)) {
// check we have a result
if ($result->num_rows > 0) {
// loop through and print out the results
while ($row = $result->fetch_assoc()) {
// output a title for each result
echo '<hr/><p>You have selected FriendShipper' .$Flight_Information_ID. ':</p> <ul>';
// loop through and output details for each item
foreach ($row as $key => $value) {
echo '<li><em>'.$key.'</em> = <strong>'.$value.'</strong></li>';
}
// output a horizontal rule under the result
echo '</ul><hr/>';
}
// num_rows = 0, no results found
} else {
echo "<p>No Flights Found " .$Flight_Information_ID. "</p>";
}
// if there was an error with your query, this will display it
} else {
echo "SQL Error: " . $db->error;
}
}
?>

check if MySQL table is empty

I want to check if my table is empty I've tried this "which I think that is the solution"
$test_empty="SELECT *FROM objectif where 1 ";
if(empty($test_empty))
{
echo "I m here";
}
But it seems that it doesn't work.
Depending on how you are connecting to your database (for example, using mysqli):
$db = new mysqli("localhost","username","password","dbname");
$check = $db->query("SELECT COUNT(*) FROM objectif");
if ($check->num_rows == 0 || $check->fetch_field() == 0){
echo "table is empty";
}else{
echo "table is not empty";
}
Currently, your code isn't actually connecting to the database or querying the table - you are essentially just checking if the variable $query is empty (which it never will be, as it contains a string!
Running a query to fetch the number of records and checking that as per the code above is one way to do this.
Use this
$mysqli = new mysqli("localhost","root","","db");
if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{
if ($obj = $result->fetch_object())
{
echo "NOT EMPTY";
}
else
{
echo "empty";
}
$result->close();
}
$mysqli->close();
Please try below code :
$test_empty="SELECT * FROM objectif";
$query = mysql_query($test_empty);
if(mysql_affected_rows() > 0)
{
echo "It is Empty";
}

IF VAR is in mySQL database then return that rows data as variable PHP

I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?

PHP MySQL - Function

i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){

PHP Function within a function within a loop :S

Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}

Categories