Added if else argument and lost variable from database - php

<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
while($row = mysqli_fetch_array($result))
{
if (!empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $row['Price'] * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
}
mysqli_close($con);
?>
This is returning the "Not Applicable" from the if argument every time.
I've tried placing the lines in different order and using both the price and result variable, it still only returns not applicable but without the if else argument, the rest of it works as intended and brings up a price so I know the price variable shouldn't be empty and neither should the result variable.
With it returning not applicable all the time, I assume it's not retrieving the information from the database properly any more but I can't figure out why when it works perfectly fine without the if else.
Any help would be great, Thanks.

Your logic is wrong:
if (!empty($row['Price']))
^ here
{
echo "Not Applicable";
}
should be:
if (empty($row['Price']))
{
echo "Not Applicable";
}
You also have a serious sql injection problem, you should use prepared statements or at the very least use mysqli's escaping function.

if (empty($row['Price']))
{
echo "Not Applicable";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet'
.....
}
}
I think the in the if condition the negation causes the problem
Remove the exclamation mark!

It might be because you are using mysqli_fetch_array instead of mysqli_fetch_assoc. http://www.php.net/manual/en/mysqli-result.fetch-assoc.php
You should also start using real_ escape_ string on your parameters, or do it in the right way with parameterized prepared statement. http://www.php.net/manual/en/mysqli.prepare.php

<?php
$con=mysqli_connect("localhost","root","","clarks");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$place = $_GET['place'];
$place2 = $_GET['place2'];
$return = $_GET['return'];
$people = $_GET['people'];
$pickup = $_GET['pickup'];
$dropoff = $_GET['dropoff'];
$result = mysqli_query($con,"SELECT * FROM pricelist WHERE place1='$place' AND place2='$place2' AND people='$people'");
$row = (mysqli_fetch_array($result));
$a = $row[3];
if (empty($a))
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>";
echo "N/A";
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
else
{
echo "<html><body style='background-color: #31ff01;'><link rel='stylesheet' href='css/bootstrap.min.css'>";
echo "<div id='prices'>£";
echo $a * $return + $pickup + $dropoff;
echo "</div>";
echo "<div id='back'>";
echo "<a href='index.html'>Go Back</a>";
echo "</div>";
echo "<br>";
}
mysqli_close($con);
?>
Well I found this workaround, instead of using while I just got rid of it and assigned the price from the database into its own variable meaning there's no conflict with the if else statement. Works like a charm... now to look at prepared statements :S

Related

How to accept a PostgreSQL database quantity in a php script?

This is the simple snippet of code that I'm trying to edit for a school project. The problem as far as I can understand, is that its fetching the quantity right but it may not be getting stored in the variable $quantity. I've tried debugging it to no success. Also, The simple addition is giving bizarre results.
Please help. The code is as follows
<?php
include("DB.php");
$id = $_POST["flower_id"];
$add_quantity = $_POST["quantity"];
echo "FlowerID";
echo $id;
echo "<br>";
echo "Add Quantity";
echo $add_quantity;
echo "<br>";
$con = pg_connect("host=localhost dbname=kruttika user=kruttika");
$quantity = pg_query("select quantity from inventory where flower_id='$id'");
$new = $quantity;
echo "Fetched Quantity";
echo $new;
echo "<br>";
if(!$con)
echo "Error<br>";
else
{
$new_quantity = $new + $add_quantity;
echo "Total Quantity";
echo $new_quantity;
echo "<br>";
$sql = "update inventory set quantity=$new_quantity where flower_id='$id'";
echo "SQL injected";
echo $sql;
echo "<br>";
$result=pg_query($sql);
}
echo $result;
echo "<br>";
//echo "<script>location.href=\"adminindex.html\"</script>";
?>
I think the problem is:
$quantity = pg_query("select quantity from inventory where flower_id='$id'");
pg_query() doesn't return the actual value, it returns a pg_fetch_result().
You must fetch the result to get the desidered value. See the examples on the documentation linked above.

ELSE condition is not working in the while loop in PHP

<?php
$conn=mysqli_connect("localhost","id6755695_artemi8","sharanod"
,"id6755695_user_info");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$department = $_POST["department"];
$year = $_POST["year"];
$sem = $_POST["semester"];
$reg = $_POST["regulation"];
$sql = "SELECT book_name, author, edition, image FROM dept_search WHERE
department='$department' AND year='$year' AND semester='$sem' AND
regulations='$reg' ";
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
if($row)
{
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
else
{
echo "sorry book not found";
}
}
mysqli_close($conn);
?>
please help me with this code,i am building a library management system.. The thing is I should be able to display the books if the given values are present i have in the database if not book not found must be displayed but in while loop after if, else does not runs.....
As others have pointed out, your else statement will never run. If you are already inside the while loop, you will certainly have $row defined and for that reason, else will never run.
What you can do is, check beforehand if the query returned actual results, like so:
$result=mysqli_query($conn,$sql);
if($result->num_rows > 0){
while($row = mysqli_fetch_assoc($result)){
echo "<br>";
?>
<img src=" <?php echo $row['image']; ?> " height="300" width="300">
<?php
echo "<br>";
echo "<b>",$row['book_name'],"</b>";
echo "<br>";
echo $row['author'];
echo "<br>";
echo $row['edition'];
}
}else{
echo "Sorry book not found";
}
You can try with mysqli_num_rows .. sample code as follows :
$rowcount=mysqli_num_rows($conn,$sql);
if($rowcount!=0){
$result=mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
?>
You are looping through all the rows returned from the "mysqli_fetch..." command. Your "if" and "else" is useless -- you will always have rows. If you get no rows, you do not even enter the body of the while loop.
You need to COUNT the rows returned (count($row)) and display a message that nothing was found if the count is less than one.
All you need to do is that you have to change if the condition from if($row) to if($other_condition)
Currently, you are just checking either there is something inside $row, and this condition will never be wrong unless you will assign it null. Because where $row will have something then while loop will be executed, and when while loop will be executed then if condition will be executed.
you have to simply one thing, that is to change if condition like given below...
if($row['value'] == 'something')

Panel List Php not showing all data

I am trying to create a panel list that shows certain rows from my database, however when I'm trying to call it, it only shows 1 data in the row even though i limit it by 5.
Here is my script:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM updates order by id desc limit 5";
if($result = mysqli_query($link, $sql)){
if($list=mysqli_fetch_array($result)){
echo "<div class=\"container\">";
echo "<table>";
echo "<tr>";
echo "</tr>";
echo "<div class=\"col-md-4\">";
echo "<div class=\"panel panel-primary\">";
echo "<div class=\"panel-heading\">Updates";
echo "</div>";
echo "<ul class=\"list-group\">";
echo "<li class=\"list-group-item\">";
echo "<b><h4>{$list["updates"]}</b></h4>";
echo "</li>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</div>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
That's because you are fetching only once, here:
if ($list=mysqli_fetch_array($result) )
Instead wrap this up inside a loop like this:
$row_count = mysqli_num_rows($result);
if ($row_count <= 0) {
echo "No records matching your query were found.";
}
else {
// you have results
// panel starts here
while ($list = mysqli_fetch_array($result)) {
// do some magic with your results
}
// panel ends here
mysqli_free_result($result);
}
I think you got the idea, now you can do the rest. If not let us know again. Happy coding!
You use sql to get five data, but you use mysqli_fetch_array() function only took out a line.
error line 8;

For loop retrieves same mysql row

I’m trying to retrieve the first 4 entries with a for loop, but it seems to repeat 1 entry 4 times.
This is my code:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten");
while($row = mysqli_fetch_array($result)) {
for ($result = 1; $result <= 4; $result++) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
}
mysqli_close($con);
You don't need a for loop. I've modified code, to retrive only first 4 items.
Look at the cahnged query LIMIT 4.
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
?>
You have a for loop inside the while loop. You can remove the for loop and use LIMIT from MySQL (which is better as fetching all entries by PHP (better performance), if you need only the first 4 entries):
SELECT * FROM activiteiten LIMIT 4
If you still want to do it with php:
$results = 0;
while($row = mysqli_fetch_array($result) && $results < 4) {
echo "<div class='agenda_item' style='background-color:#F39'>";
...
$results++;
}
Your code—as presented—mixes things up in ways that behave the way you see. The for loop is not needed. And you should set a LIMIT in your MySQL query like this:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 0,4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
The problem with your original code is mixing for with while ends up in the scenario you showed as explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.
So you have a while iterating over the results, but then you also have for loop nested in there. 100% unnecessary.
The way I adjusted it is to just removed that for loop, but also add LIMIT 0,4 to the MySQL query. That basically tells MySQL to fetch 4 rows beginning from the first row which is referred to as 0.

how to set empty space when records is not into data base

i am created html form ,when i click on submit button i get records from data base,but if the data is not in to the data base its print
http://bukkyolu.com/mp3/upload/
that not come form database its just static value that i am print in statement bellow
http://bukkyolu.com/mp3/upload/".$row['2']."'> ,
if the .$row['2'].is not in to database
i want empty space not default link that printed
<?php
$category=$_POST["category"];
$month=$_POST["month"];
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "bukkyolu_mp3";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
$query = "SELECT title,Amp3,Bmp3,Cmp3 FROM mp3_data WHERE`category` = '$category' and `month` = '$month' ";
$result1 = mysql_query($query);
$row = mysql_fetch_array($result1);
//echo $row['s_id'];
echo "<table border='1' align='center' >";
while ($row = mysql_fetch_row($result1)){
// echo "<td><a href='#' onclick='someFunction()'>" .$row['0']. "</a> </td>";
echo "<tr><th>Title:</th><td>".$row['0']."</td></tr>";
echo "<tr><th>African:</th><td><a href 'http://bukkyolu.com/mp3/upload/".$row['1']."'>http://bukkyolu.com/mp3/upload/".$row['0']."</a></td></tr>";
echo "<tr><th>British:</th><td><a href 'http://bukkyolu.com/mp3/upload/".$row['2']."'>http://bukkyolu.com/mp3/upload/".$row['0']."</a></td></tr>";
echo "<tr><th>Caribbean:</th><td><a href 'http://bukkyolu.com/mp3/upload/".$row['3']."'>http://bukkyolu.com/mp3/upload/".$row['3']."</a></td></tr>";
echo "<tr></tr>";
echo "<tr></tr>";
}
echo "</table>";
?>
Check for the value as below.
if(isset($row['0']) && $row['0'] != "")
{
echo "<tr><th>African:</th><td><a href 'http://bukkyolu.com/mp3/upload/".$row['1']."'>http://bukkyolu.com/mp3/upload/".$row['0']."</a></td></tr>";
}
else
{
echo "<tr><th>African:</th><td>...</td></tr>";
}
Do the same for other.
OR
Create function that will more like a good programming habit.
function checkForValue($value)
{
$response = "&nbsp";// you can also add ... or anything
if(isset($value) && $value != "")
{
$response = $value;
}
return $response;
}
and call it as .
echo "<tr><th>Title:</th><td>".checkForValue($row['0'])."</td></tr>";
try this:
isset($row['0'])?$row['0']:''
while ($row = mysql_fetch_row($result1)){
// echo "<td><a href='#' onclick='someFunction()'>" .$row['0']. "</a> </td>";
echo "<tr><th>Title:</th><td>".isset($row['0'])?$row['0']."</td></tr>";
echo "<tr><th>African:</th><td><a href 'http://bukkyolu.com/mp3/upload/".isset($row['1'])?$row['1']:''."'>http://bukkyolu.com/mp3/upload/".isset($row['0'])?$row['0']:''."</a></td></tr>";
echo "<tr><th>British:</th><td><a href 'http://bukkyolu.com/mp3/upload/".isset($row['2'])?$row['2']:''."'>http://bukkyolu.com/mp3/upload/".$row['0']."</a></td></tr>";
echo "<tr><th>Caribbean:</th><td><a href 'http://bukkyolu.com/mp3/upload/".isset($row['3'])?$row['3']:''."'>http://bukkyolu.com/mp3/upload/".isset($row['3'])$row['3']:''."</a></td></tr>";
echo "<tr></tr>";
echo "<tr></tr>";
}
echo "</table>";
etc in this way you can set space if value does not exits
hope it will help!
Add additional condition that if your query has no results found.
It will just do else with no mysql_fetch_rows because mysql_fetch_rows needed outputs to be fetch..
if(count($result1) > 0){
while ($row = mysql_fetch_row($result1)){
// echo "<td><a href='#' onclick='someFunction()'>" .$row['0']. "</a> </td>";
echo "<tr><th>Title:</th><td>".(!empty($row['0'])? $row['0']: ' '."</td></tr>";
echo "<tr><th>African:</th><td><a href '".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['0'] : ' '."'>".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['0'] : ' '."</a></td></tr>";
echo "<tr><th>African:</th><td><a href '".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['2'] : ' '."'>".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['0'] : ' '."</a></td></tr>";
echo "<tr><th>British:</th><td><a href '".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['3'] : ' '."'>".(!empty($row['0']))? 'http://bukkyolu.com/mp3/upload/'.$row['3'] : ' '."</a></td></tr>";
echo "<tr></tr>";
echo "<tr></tr>";
}
}
else{
echo "<tr><th>Title:</th><td> </td></tr>";
echo "<tr><th>African:</th><td><a href 'javascript:void(0);'> </a></td></tr>";
echo "<tr><th>African:</th><td><a href 'javascript:void(0);'> </a></td></tr>";
echo "<tr><th>British:</th><td><a href 'javascript:void(0);'> </a></td></tr>";
echo "<tr></tr>";
echo "<tr></tr>";
}
try to include ternary condition in each of your result
so that if the fetch data is empty it will display the other condition as ' '

Categories