zero not disappearing [duplicate] - php

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 8 years ago.
$i=0;
$sql = $dbh->prepare('SELECT kappaleen_nimi, levy_id, kesto FROM kappaleet');
$ok = $sql->execute();
if(!$ok) { print_r( $sql->errorInfo() ) ; }
while($row = $sql->fetch(PDO::FETCH_ASSOC) ) {
foreach($row as $value) {
if($value!=null || $value!=0){
$haku2[$i] = $value;
$i=$i+1;
}
}
}
I'm working with this sql database, where i'm fetching kappaleen_nimi (name of the track), levy_id (record_id) and kesto (length) from the sql table kappaleet. I'm trying to remove fields containing null or 0. However, the final zero gets through anyway through this filter: "if($value!=null || $value!=0)".
When printing my table the following way:
foreach($haku2 as $value){
echo $value.', ';
}
I get this kind of result (last few fields): "Sateen tango, 7, 3.11, 0, "
The final zero is still there, and i can't get my head around it, why the he** it passes the if condition... I know that the final zero is levy_id (record_id).

I think you are looking for an AND conditional instead of an OR. To fix this, replace the following line
if($value!=null || $value!=0){
with this one
if($value!=null && $value!=0){

Related

Accidental infinite while loop in PHP [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 6 years ago.
Hi I have created a while loop but cannot understand why it loops forever. Could somebody please explain why?
while ($i<3){
if ($i=1){
$x='psu';
}else if ($i=2){
$x='cases';
}
$sqlcpu = "SELECT * FROM $x WHERE name LIKE '%{$term}%'";
$query = mysqli_query($db, $sqlcpu);
while ($row = mysqli_fetch_array($query)){
?><br /> Name: <?php echo $row['name'];?>
<?php
echo ' Price: £'.$row['price'];
}
$i++;
}
There are other problems with this code but they are not my main concern right now as this loop seems like it should be simple. The variables $x and $i never change after $i=1
if ($i=1) You're assinging 1 to $i here, instead of comparing 1 and $i, use
if ($i==1)
instead.
Instead of the for/if-elseif construct you could also use
foreach( array('psu', 'cases') as $table ) {
$sqlcpu = "SELECT * FROM $table WHERE name LIKE '%{$term}%'";

Issue with if statement variable [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 7 years ago.
I am trying to create this simple if statement, but I am running into issues with the variable $testnumrows. In this if condition I am trying to see if there are any group columns with data and if so echo the amount of rows, but I want nothing to show up if there isn't.
In my db I have 6 rows that have what I mentioned in the query. The output that is showing up on the page is 0 though, so it seems my variable is being reset.
Before I had this:
$testnumrows = mysqli_num_rows($test);
echo " " . $testnumrows;
and it read the 6, I just can't get the if statement to work.
Here is the full code now.
<?php
$con = mysqli_connect("localhost", "", "", "");
$test = mysqli_query($con,"SELECT `group` FROM user_requests WHERE `group` = 1");
$testnumrows = mysqli_num_rows($test);
if($testnumrows = 0) {
echo "";
} else {
echo " " . $testnumrows;
}
?>
It should read if($testnumrows == 0) {.
Trivial error = instead of ==
Solution:
if($testnumrows == 0) {
echo "";
} else {
echo " " . $testnumrows;
}
Change if($testnumrows = 0) to if($testnumrows == 0).

PHP Ajax return more than one row from database [duplicate]

This question already has answers here:
How do I loop through a PHP array containing data returned from MySQL?
(6 answers)
Closed 8 years ago.
I wrote some PHP and Ajax code in order to see my inventory when I type in a location name. Here is an image of my inventory. Notice most of the locations contain more than one kind of items.
And here is the front end interface I have.
Here's the part of the code I have problems with.
<?php
// '.post' could be '.get' here but global.js has to be the same, .post is faster
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `sheet0_100`.`id`
FROM `sheet0_100`
WHERE `sheet0_100`.`location` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_fetch_row($query) : 'Location not found..';
}
?>
If you notice mysql_fetch_row part, when I type in a location, for instance, 50A-3, it returns a word "Array" instead of the record. Same result for those locations have more than one rows. I wonder what do I have to do with $query so that the webpage can display all the rows from a location? Thanks!
If you must use the mysql_* extension functions, in order to retrieve and therefor display multiple rows, use a while loop:
<?php
// '.post' could be '.get' here but global.js has to be the same, .post is faster
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `sheet0_100`.`id`
FROM `sheet0_100`
WHERE `sheet0_100`.`location` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
if(mysql_num_rows($query) !== 0){
while ($row = mysql_fetch_row($query)) {
// output results using the $row array
}
}
else {
echo('Location not found..');
};
}
?>
mysql_fetch_row fetches each row one at a time

PHP foreach loop to insert data into mysql with PDO only inserts first row

I've read every question/tutorial I could find on inserting things via foreach & PDO, but am still left scratching my head.
I am basically trying to do a batch insert/update of a table based on who's paid dues in my business fraternity (hence the 'brother'/'bro).
The fields are all being retrieved from POST, field 1 is the dues amount ($amount), field 2 is number of people who have paid ($num_paid) and field 3 is an array of user ids for those who have paid ($paid) which is created via check-boxes created by a foreach loop in another file.
The best way I could think to check to make sure things were entered correctly was to compare count($paid) to $num_paid, and proceed only if they matched. I'm open to suggestions on doing that better, but it seems to work the way it is.
I'm trying to loop through the array from field 3 ($paid) using 'foreach' to insert new rows in the table as a 'credit' for each person who has paid, but for some reason it only inserts in the first loop, then somehow inserts empty rows for the rest.
The table is set up with columns: user_id(manually input), transaction_id(AI), date, credit, debit, info.
Using: "INSERT INTO finance VALUES(?,NULL,now(),?,?,?)"; If I insert 5 users, it will insert the first with transaction_id x, then run up the auto-increment count 4 more, but insert nothing. So the next time I try inserting, the transaction_id is 5 more than the first.
e.g. -- Try 1 inserts a row with transaction_id 43. Try 2 inserts one row, with transaction_id 48, but there's nothing in between them.
I've tried passing the array into the function, then looping through it with 'foreach' that way, and also tried using a 'foreach' loop which calls the function and passes it a string each time to insert. Both seem to work the same. I'm pretty lost, because it seems like if the auto incrementing column is counting up, it should be inserting data?
I think this is all the relevant code...(PHP tags were added to make it more readable.)
Processing of form data which calls the function
<?php
if (isset($_POST['amount']) &&
isset($_POST['num_paid']) && isset($_POST['paid'])) {
$amount = saniString($_POST['amount']);
$num_paid = saniString($_POST['num_paid']);
$paid = $_POST['paid']; #this is an array of user id's for
#who has paid.
echo "<br /><br />";
var_dump($paid);
echo "<br /><br />";
var_dump($num_paid);
echo "<br /><br />";
var_dump($amount);
echo "<br /><br />";
if (count($paid) != $num_paid) {
echo "<p><b>You did not check the correct number of
brothers. Please check your entries and try again.</b></p>";
}
elseif (count($paid) == $num_paid) {
$match = true;
echo "<p><b>Congrats. The numbers match.</b></p>";
}
if ($match === true) {
if ($amount > 0) {
$credit = $amount;
$debit = 0;
}
elseif ($amount < 0) {
$credit = 0;
$debit = $amount;
}
else {
$credit = 0;
$debit = 0;
}
foreach ($paid as $dirtyId) {
$result = updateFin($dirtyId,$broid,$credit,$debit,$dbh);
var_dump($result);
}
}
}
?>
Function to prepare/bind/insert
<?php
function updateFin($dirtyId,$broid,$credit,$debit,$dbh) {
$sql = "INSERT INTO finance VALUES(?,NULL,now(),?,?,?)";
$query = $dbh->prepare($sql);
#foreach ($paid as $dirtyId) { // please notice this is commented out
$bro_paid = saniString($dirtyId);
$info = "Dues from bro-ID: " . $bro_paid;
$query->bindValue(1, $broid);
$query->bindValue(2, $credit);
$query->bindValue(3, $debit);
$query->bindValue(4, $info);
try {
$result = $query->execute();
}
catch (PDOException $e) {
echo "<br />Insert of $credit, with info $info failed.";
echo $e->getMessage();
$result = false;
}
return $result;
#}
}
?>
var_dumping the values I'm trying to pass in gives me what I'd expect - $amount is a string (50.00), $num_paid is also a string (5), and $paid is an array full of the IDs I'm trying to insert...
The 'saniString' function uses strip_tags, htmlentities, and stripslashes, if that's relevant...
If I var_dump($result) it returns bool(true),bool(false),bool(false),bool(false),bool(false). Which is what I'd expect given my results, except I have no idea why the queries are failing and I'm not getting any error messages from PDO?
The issue is caused by the unique on date. The subsequent inserts have a date the same down to the second and so they're ignore (while the autoincrement is incremented).
So
alter table finance drop index date
[EDITED]
The setting $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); should have caused the duplicate inserts to throw an exception with SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry (It does when I test it) But this attribute isn't set by default when the PDO-object is created.
When in doubt, you can always fall back to checking the error info, even if there isn't an exception. $err = $query->errorInfo();, for a duplicate entry you'll get $err[1] == 1062
In this line if (count($paid) != $num_paid) { you are not defining $match and if this statement gets true than this line will raise an error of undefined variable $match if ($match === true) {
Replace this code block
if (count($paid) != $num_paid) {
echo "<p><b>You did not check the correct number of
brothers. Please check your entries and try again.</b></p>";
$match = false;
}
elseif (count($paid) == $num_paid) {
$match = true;
echo "<p><b>Congrats. The numbers match.</b></p>";
}

How to do something different for the last item in an array (from mysql_fetch_array)? [duplicate]

This question already has answers here:
Echo a comma on all but the last value? (result from mysql_fetch_array)
(11 answers)
Why doesn't it prevent further looping?
(2 answers)
Closed 8 years ago.
I am trying to make sure that commas go after all of the items EXCEPT for the last one - I am trying to figure out how to calculate out what the last item is for variable lists. I decided to try to use count($variablename) but it doesn't seem to work.
Is there something wrong with my syntax?
$servicearray = mysql_query("select serv_id from org_serv_xref where org_id='".$org_id."'");
$servi = 0;
while ($servicearrayrow = mysql_fetch_array($servicearray)) {
$servdescarray = mysql_query("select serv_desc from service where serv_id='".$servicearrayrow['serv_id']."'");
while ($servdescarrayrow = mysql_fetch_array($servdescarray)) {
if ($servi < 5 OR $servi < count($servdescarrayrow)) {
ECHO $servdescarrayrow['serv_desc'].",";
$servi++;
}
else if ($servi == 5 OR $servi == count($servdescarrayrow)) {
echo $servdescarrayrow['serv_desc'];
$servi++;
}
else {
$servi = 0;
break 2;
}
}
}
Because you're starting $servi at 0. It will always be less than the count of the array. If you start it at 1 it should work the way you expect it to.
change your query to
$servicearray = mysql_query("select GROUP_CONCAT(serv_id) from org_serv_xref where org_id='".$org_id."'");
now sql builds the nice comma delimited list for you :)
As near as I can figure, your trying to do something like this (although I could be totally wrong):
// Initialise vars
$lastid = '';
$items = array();
// Do the query
$query = "SELECT serv_desc, serv_id
FROM service
WHERE serv_id IN (
SELECT serv_id
FROM org_serv_xref
WHERE org_id='".$org_id."'
)
ORDER BY serv_id";
$servdescarray = mysql_query($query);
while ($servdescarrayrow = mysql_fetch_assoc($servdescarray)) {
// We've reached the next ID, echo the result of the last one.
if ($lastid != $servdescarrayrow['serv_id']) {
$lastid = $servdescarrayrow['serv_id'];
if (count($items)) {
echo implode(',',$items);
$items = array();
}
}
if (count($items) == 5) { // We don't want more than 5 items
continue;
} else { // Add an item to the results
$items[$servdescarrayrow['serv_desc']];
}
}
// Make sure we get the last one
if (count($items)) {
echo implode(',',$items);
}

Categories