Check if fields is complete and Insert new data - php

Hello so I have a table named tables that contains 9 fields (`id, first, second, third, fourth, fifth, sixth, seventh, eight) and if all of those fields aren't empty, I want to insert it as new records on the same table. This is my code for now:
$db = new db();
$bind = array(
":tid" => "1"
);
$results = $db->select("tables", "tableID = :tid", $bind);
foreach ($results as $r) {
$tableID = $r['id'];
$l1_1 = $r['first'];
$l1_2 = $r['second'];
$l1_3 = $r['third'];
$l1_4 = $r['fourth'];
$l1_5 = $r['fifth'];
$l1_6 = $r['sixth'];
$l1_7 = $r['seventh'];
$l1_8 = $r['eight'];
}
if($l1_1 != "" AND $l1_2 != "" AND $l1_3 != "" AND $l1_4 != "" AND $l1_5 != "" AND $l1_6 != "" AND $l1_7 != "" AND $l1_8 != "")
{
$db->insert("tables", array(
"first" => $l1_1,
"second" => $l1_2,
"third" => $l1_3,
"fourth" => $l1_4,
));
//insert 2nd record
$db->insert("tables", array(
"first" => $l1_5,
"second" => $l1_6,
"third" => $l1_7,
"fourth" => $l1_8,
));
}
I also have a long code that the summary of what it does is to check if field is empty and insert that data there, until all fields are filled. When the last data is entered, the code above will execute. When the last data is entered, it will do the code above that will check if all fields is empty and insert a new data. This code works but the last data being inserted appears blank in the new record being inserted.
I know my explanation is vague, but please just ask me what you want to know.

I believe your answer lies in your If statement. You are checking if the fields are "", or blank. This is incorrect as they could be NULL in the database. There is an answer out there that explains how you can resolve it.
Better way to check variable for null or empty string?
Change your code as follows:
if(isset($l1_1) && trim(($l1_1) != ''
AND isset($l1_2) && trim(($l1_2) != ''
AND isset($l1_3) && trim(($l1_3) != ''
AND isset($l1_4) && trim(($l1_4) != ''
AND isset($l1_5) && trim(($l1_5) != ''
AND isset($l1_6) && trim(($l1_6) != ''
AND isset($l1_7) && trim(($l1_7) != ''
AND isset($l1_8) && trim(($l1_8) != '')

Related

Filtering ARRAY and grabbing distinct entry

Currently I am collecting a count of desktop and mobile devices... the count is coming back correctly based in the items total in the ARRAY. But, now I need to remove duplicates... Example user_id = 001 can have 10 entries for IOS ... so I would need to do something like ... IF $row['last_login'] Date() is the most current then grab that entry and count as 1. End result for user_id = 001 would be 1 entry count and not 10 (which I am getting now).
if ($results = $dbh->runQuery($sql)) {
foreach ($results as $key=>$row){
$users[$row['user_id']][] = array('user_id'=>$row['user_id'],
'racid' => $row['racid'],
'email' => $row['email'],
'last_login' => $row['last_login'],
'fname' => $row['fname'],
'lname' => $row['lname'],
'role_id' => $row['role_id'],
'role_name' => $row['role_name'],
'ios_device_token' => $row['ios'],
'roid_device_token' => $row['roid'],
'p_name' => $row['p_name']);
if($row['ios'] !== null && $row['ios'] !== '' && $row['ios'] !== '-1'){
$ios_count++;
}
if($row['android'] !== null && $row['android'] !== '' && $row['android'] !== '-1'){
$android_count++;
}
$invalidValues = [null, "", -1];
if(in_array($row['ios'], $invalidValues) && in_array($row['android'], $invalidValues)){
$desktop_count++;
}
}
}
Using associative arrays, you can "distinctify" by your own criterium. Something like the following code.
However what #esqew said (commenting your question) about altering the SQL instead of the PHP is probably a cleaner angle, especially since PHP is generally quite slow.
if ($results = $dbh->runQuery($sql)) { // that exists already
$latestEntries = []; // assoc. array: key=user, value=row
foreach ($results as $row) { // that exists already
// assuming 'last_login' is a timestamp or any format that can be used in inequality
// otherwise cook your own comparison function
if (
!$latestEntries[$row['user_id']]
|| $latestEntries[$row['user_id']]['last_login'] < $row['user_id']['last_login']
) {
$latestEntries[$row['user_id']] = $row;
}
// rest of your code that exists already
}
// here, after the loop, $latestEntries has the latest entry for each user found in $results
}

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.

Make a difference between empty value and 0

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...
}

PHP mysql Query Builder that displays just what I want

I'm relatively new to PHP and I need some help on a search query.
I have a few drop down 'select' and a 'checkbox group' which will filter the search from database using (...WHERE somethingA = 'somethingA' && somethingB = 'somethingB' etc)
That's all working great but the problem comes when I want to make it so that some search fields DONT have to be used, so if 'SomethingA' is either disabled or value='none' then it will only return WHERE somethingB = 'SomethingB'.
I have tried using OR instead of AND but that returns both values if they are true and not really filtering it properly.
my initial solution was to have if..else statements to define the query,
for example:
$query = "SELECT * FROM table";
$results = $con->query("$query $where $QueryA $QueryB $QueryC");
if($_GET['SomethingA'] == "none" && $_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = ""
$QueryA = ""
$QueryB = ""
$QueryC = "ORDER by ID" //if all search field is 'none' then get all results
}elseif($_GET['SomethingB'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = "SomethingA = '{SomethingA}'" //only use A filter one field
$QueryB = ""
$QueryC = ""
}elseif($_GET['SomethingA'] == "none" && $_GET['SomethingC'] == "none"){
$where = "WHERE"
$QueryA = ""
$QueryB = "SomethingB = '{SomethingB}'" //only use B filter one field
$QueryC = ""
.....
it works but you can already see the problem as if i wanted to cross matrix all conditions it becomes very lengthy and confusing.
So my question is whether there is a much better way of doing this, for instance, make value='none' return all results?
been looking around and attacking it from many angles but cant find a solution..
maybe javascript could help but im not the best with it.
thanks in advance
The question is not too clear but look into this. It should help.
$query="SELECT * FROM table WHERE";
$query_link = " AND ";
$isASet=false;
$isBSet=false;
$isCSet=false;
if(strcmp($_GET['SomethingA'],"none") != 0){
$query.=" column = {$_GET['SomethingA']}";
//set this to true for later if statements
$isASet=true;
}
if(strcmp($_GET['SomethingB'],"none") != 0){
//check if A has been set, if yes include an AND
if($isASet){
$query.=$query_link;
}
//include this one as usual
$query.=" column = {$_GET['SomethingB']}";
$isBSet=true;
}
if(strcmp($_GET['SomethingC'],"none") != 0){
//check if A or B has been set, if yes include an AND
if($isASet || $isBSet){
$query.=$query_link;
}
//include this as usual
$query.=" column = {$_GET['SomethingC']}";
}
//run query and collect result
$result = $connection->query($query);

If or statement in php not evaluating correctly

I have this PHP statement:
if (($row['rest'] != "") or ($row['rest'] != "Select An Option")) {
$rest = "<b>Rest Stops:</b> {$row['rest']},";
}
else {
$rest = "";
}
which is not evaluating properly and I can't figure out why. What I want the statement to do is if the field 'rest' is blank or "Select An Option" then the variable $rest should evaluate to "Rest Stops:" followed by the data. My data is "Select An Option" and I get "Rest Stops: Select An Option" as the output. I did some testing of this statement and I figured out PHP is assigning the variable $row['rest'] as not equal to "" instead of evaluating the 'or' statement. What would be the correct syntax?
What I want the statement to do is if the field 'rest' is blank or Select An Option than the variable $rest should evaluate to Rest Stops: followed by the data.
Your logic is incorrect. You need to check if they are equal to, so use == instead of !=.
if ($row['rest'] == "" || $row['rest'] == "Select An Option") {
^--------------------^ ^--------------------------------^
if field 'rest' blank if field is 'Select An Option'
This can be be improved by using empty() to perform the "is empty" check:
if (empty($row['test']) || $row['rest'] == "Select An Option") {
"If the field 'rest' is blank ...." - if that's true, then your logic is backwards:
if ($row['rest'] == '') || ($row['rest'] == 'Select an option') {
$rest = 'rest stops';
} else {
$rest = '';
}
Note the use of == for equality, rather than != for inequality.

Categories