Make a difference between empty value and 0 - php

Its' about a form to enter results of a soccer tournament.
The form got the already inputed data from the db and writes it into the value argument of the html form. If the value in the db NULL so in the html i got
value=""`
It's important that games with no inputs doesn't make a change in the db so i filter it before i do the query. But now could it happen that a game ends 0 : 0 But the db won't safe that. How can i say the system its not empty/NULL it is 0?
if(!empty($_POST[$tore_heim] OR !empty($_POST[$tore_gast]))){
$spiele_save = "UPDATE spiele SET tore_heim = '".$_POST[$tore_heim]."', tore_gast = '".$_POST[$tore_gast]."' WHERE id_spiele = ".$spiele_id[$i]."";
$spiele_save = mysqli_query($con, $spiele_save);};
};

Thank you deceze
if(isset($_POST[$tore_heim]) && strlen($_POST[$tore_heim]) > 0
OR
isset($_POST[$tore_gast]) && strlen($_POST[$tore_gast]) > 0)
The Problem is solved!

Check if value is '0': !empty($_POST[$tore_gast])) || $_POST[$tore_gast] === '0'

look at this example.
function isEmpty( $variable ){
return (
!isset($_POST[$variable]) ||
( empty($_POST[$variable]) && $_POST[$variable] !== "0" )
);
}
if ( !isEmpty($tore_heim) ){
// run your code here...
}

Related

Check if an array value is set or not

I'm fetching practice_string_id and program_string_id from a table
$project_type = DB::table('project')
->where('code',$asset_request->project_code)
->select('practice_string_id','program_string_id')
->first();
print_r($project_type); //output
Output:
stdClass Object ( [practice_string_id] => PRACTICE0028
[program_string_id] => )
I want to check $project_type->program is set or not in if condition
if(isset($project_type->program_string_id)){
//nothing in $project_type->program but reached here now
}
I want to how to check the value is set or not in php if condition.now if(isset($project_type->program_string_id)) is passed and if condition is working.I want to skip if condition.
As this is a database query, and you select the field program_string_id, it will be set always and any time. The question is, if there is any value. So you might want to use empty as check:
if (!empty($project_type->program_string_id)) {
// ...
}
if(isset($project_type-> program_string_id) && !empty($project_type-> program_string_id) )
}
You have to use both isset() and empty() other wise it may throw error in some cases
$project_type = DB::table('project')
->where('code',$asset_request->project_code)
->select('practice_string_id','program_string_id')
->first();
if(count($project_type) > 0 && $project_type != ""){
echo $project_type->program_string_id;
}

Mysqli failing to insert boolean in prepared statement

I am trying to INSERT a new row into my db via php7.
Mysqli is throwing the error
Column 'newsletter' cannot be null
The newsletter column in the database is a tinyint(1)
Here is the code:
public function Add_User(array $data) {
if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) )
$optin = ( $data['newsletter'] === 'on' ) ? 1 : 0;
$country_code = $this->Get_Country_Code();
if( !$q = $this->_db->prepare("INSERT INTO `users` (`name`,`email`,`country_code`,`newsletter`) VALUES (?,?,?,?)") ) { printf('error on prepare'); }
if( !$q->bind_param('sssi', $data['name'], $data['email'], $country_code, $optin)) { printf('error on bind'); }
if( !$q->execute() ) { printf('error on execute'); }
printf('Insert error %s', $this->_db->error);
if( $this->_db->affected_rows == 0 ) {
// There was a problem with the insert
printf('Insert error %s', $this->_db->error);
}
$q->close();
}
I also tried adding the boolean value as a string, but it still didn't work.
Thanks in advance.
Fixed!
The issue was that I was not providing all column values ( I want to update those later, as they are not available on the html form submit ).
I needed to assign a default value for those columns which will not be filled on the initial INSERT.
The error message however was not helpful.
Shouldn't you set $optin to true/false instead of 1/0?
if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) )
$optin = ( $data['newsletter'] === 'on' ) ? 1 : 0;
Basically if the criteria for this if are not true so you don't "enter" your if your $optin variable will be null/undefined.
If you want to avoid that there are 2 ways.
1) change the accepted value in your newsletter field in the db to accept null
2)
$optin=0;
if( !isset($data['name']) || !isset($data['email']) || !isset($data['newsletter']) ){
if($data['newsletter'] === 'on' ){
$optin=1;
}
}
$country_code = $this->Get_Country_Code();
Define your variable with the "negative" value you want to be set if your criteria are not matched and change it inside your if.

variables changing during IF loop

I'm working on a PHP script to make a catalog. The relevant columns in my database are Vid, banner, category and Scategory. Vid is the primary key, banner is the path to my img files, and category and Scategory are both numbers for the their respective ID. Everything is over simplified as I'm just testing the scripts. There is currently 20 records in the table.
<html>
<head>
<style type="text/css">
</style>
</head>
<body>
<?php
require "config.php";
$sql = "SELECT Vid,banner,category,Scategory FROM display";
$result = $conn->query($sql);
$row = $result;
$min = 10;
$max = 20;
while ($row = mysqli_fetch_assoc($result)) {
implode ('', $row);
$vid = $row['Vid'];
$banner = $row['banner'];
$cid = $row['category'];
$sid = $row['Scategory'];
if ($cid = 2 && $sid = 1){
echo
'
<div style="display:inline-block;">
<div style="border-color:blue; border-style:solid;">
<a href="#test'.$vid.'">
<img src="'.$banner.'" />
</div>
</div>';
echo $vid;
echo $cid;
echo $sid;
if ($vid % 2 == 0){
echo '<br>';
}
}
}
require'close.php';
?>
</body>
</html>
Now the code runs just fine, but it gets strange I use $cid and $sid as conditions in that IF loop. Given there is 20 records, both $cid and $sid have half their values as '1' and half as '2, so when I set the IF conditions I figured it would return 5 records, but it instead returned all 20. When I echo $vid $cid and $sid, it returns the proper $vid, but $sid returns as whatever condition I set it to. For example conditions set to $cid=1 and $sid=2 returns 1:1:2, 2:1:2, 3:1:2 etc.
Now here is where it gets really strange, regardless of the condition set for $cid it returns as '1', if I set it '7' it still returns as '1'. Whereas $sid returns as whatever number is set. Also when I set either condition to null it returns nothing.
So my question is why it's acting the way it is or how it should be written if I'm writing it wrong.
Also as a side question, when I put <a> before <img> it returns the proper ID that's linked to the <img>. But when I put <a> directly after <img>, it returns the ID of the next iteration's row, and the first iteration returns blank. Anyone happen to know why that happens since regardless of their position in the statement it's still part of the same loop iteration?
You are using a single equal and assign the value to the variable. To compare values you have to use == or ===!
What is the difference between == and ===?
See the following condition to see the difference:
2 == "2" -> Equal
2 == 2 -> Equal
2 === "2" -> Not Equal
2 === 2 -> Equal
How you can avoid this on future? - Yoda condition
You can change your conditions to the following to make sure you are using the conditions on the right way. You only shoud use this for equal comparison not for >, <, <=, >=.
//throws an error
if (0 = $isNull) { ... }
//the right one
if (0 == $isNull) { ... }
== not = in your if statement.
implode line does nothing
Use double-equals instead of singles. Not:
if( $foo = 2 )
...but:
if( $foo == 2 )
Your code is changing the values instead of testing them.
Change if ($cid = 2 && $sid = 1) with if ($cid == 2 && $sid == 1). I think you did it only by mistake, since your other if is fine!
In your if statement you're using a single equals operator it needs to be == or ===

Validating Select Drop Down Array in PHP

I have the following to generate a state drop down on a form:
$states = array('State', 'Alabama', 'Alaska', 'Arizona', 'Arkansas');
echo "<select name='choose_state'>\n";
foreach ($states as $key => $state)
{echo "<option value='$key'>$state</option>\n";}
echo "</select>";
How would I go about making sure a user
1) only selects one of the options in the array
2) doesn't select the default value? ([0]=> string(5) "State")
edit: validate in php, this is for a form collecting user information before posting to a db
I tried using in_array and got stuck trying to exclude the default value
I think you're missing some checks. You should never rely on what is exacly posted, and always perform thorough checking:
$chosen_state = null;
if (array_key_exists('choose_state', $_POST))
{
$choose_state = $_POST['choose_state'];
if (array_key_exists($choose_state, $states) && $choose_state > 0)
{
// Value does actually exist in array and is not item 0.
$chosen_state = $states[$chose_state]);
}
}
Following example assumes that you're storing the key provided for the select in the var $state_key...
try this:
$max = sizeof($states) - 1; // this is the number of possible values that you have, minus the default
if($state_key != 0 && $state_key > 0 && $state_key < $max)
{
// do whatever here, you've got good data at this point
}
This also assumes that your default value is always key #0 (first in the array), by the way.
Validating form submit in php:
When you submit form in php, Select input type returns selected value in post. So you can do something like:
$selectedindex = $_POST["choose_state"];
if($selectedindex == 0)
{
echo "Default item has been selected";
}
else{
echo "Other than default item has been selected ";
//you can do further validation here for selected item
//is in between 0 and 5 if you need to do so
}

mysql_fetch_row returns value above zero despite actually being zero

I'm running the following query but $new returns 0:
$count = mysql_query("SELECT COUNT(*) FROM flagged WHERE status=0") or die(mysql_error());
$new = mysql_fetch_row($count);
if ($new != 0) {
echo "<script language=\"javascript\">$.titleAlert(\"New Logs - ($new[0])\");</script>";
}
Problem is the if-condition keeps getting met when it shouldn't when $new != 0
I even tried:
if ($new > 0) {
//update title about new logs
}
Either way, the title is still updated and I'm not sure why.
New Logs - (0)
just do
var_dump($new);
and you'll see why your if doesn't work
Not sure what you mean. $new should be an array not a scalar value per the PHP documentation.
mysql_fetch_row documentation
this code
$new = mysql_fetch_row($count);
makes $new becomes an array
try to compare it like this:
if ($new[0] != 0)
or even better, so You would be 100% sure it's what You need.
if (count($new) == 1 && intval($new[0]) != 0)
mysql_fetch_row should return an array or FALSE.
Maybe adjust your conditional to:
if ( !$new ) {
// some code here
}

Categories