Mysqli failing to insert boolean in prepared statement - php

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.

Related

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

Dynamic Table Name in Propel Query

I am wondering if you can make the Table name of the propel query dynamic(sort of like a variable variable)? An example would be like \"DynamicVar"Query::create(). I have it working in ifs like in my example below, but could get rid of quite a few lines if made more dynamically. The tables are all setup the same, so they can be treated like the same object they just have different names.
Currently have something like this happening:
//$dynamic is a result of grabbing it from a different table
//that corresponds to values passed by AJAX
$dyanmic = "Customer"
$query = null;
If( $dynamic == "Customer" ) $query = \CustomerQuery()::create();
If( $dynamic == something2 ) $query = \Table2Query()::create();
If( $dynamic == something3 ) $query = \Table3Query()::create();
If( $query != null ) {
$query->filterBy("something");
$query->find();
}
I played around with the code some, and the code below will work for dynamically changing the table as long as each table can be treated like the same object. You can define your $table and use it in this fashion for a function that returns the object that you want
function Get_Table($table,$id){
$query = null;
$queryClass = '\\'. ucfirst($table) . 'Query';
if ( class_exists( $queryClass ) ) {
$$dynamics = $queryClass::create()
->filterById($id)
->find();
if( $dynamics->getFirst() == null ) { return false; }
/** #var \Base\.ucfirst($table) $dynamic*/
$dynamic= $dynamics->getFirst();
return $dynamic;
}
//On Failure
else {
return false;
}
}

Check if fields is complete and Insert new data

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) != '')

Meta name not case sensitive

I have the below GET function that is based on regular WordPress custom field names.
When ticked, it sorts all posts that have that custom field value set to 1.
It currently works. But, I happen to have two custom fields named: 'free' and 'twofree'
When I tick 'free', it also includes 'twofree' and vica-versa. It does not seem to be case sensitive. Is there any work around to this?
<?php
/* my code starts from here*/
if( isset( $_GET['show'] ) && !empty ( $_GET['show'] ) ){
if( $_GET['show'] == 1 )
$meta_field = 'free';
else if( $_GET['show'] == 4 )
$meta_field = 'sale';
else if( $_GET['show'] == 2 )
$meta_field = 'genuine';
else if ( $_GET['show'] == 'onfire' )
$meta_field = 'onfire';
else if( $_GET['show'] == 5 )
$meta_field = 'twofree';
else if( $_GET['show'] == 3 )
$meta_field = 'onfire';
if( $_GET['show'] == 'sale' )
query_posts('cat='.$cat.'&meta_key='.$meta_field.'&meta_value > 0');
else
query_posts('cat='.$cat.'&meta_key='.$meta_field.'&meta_value>=1');
}
/* my code ends from here*/
?>
EDIT: I have found the problem and it lied in the part
query_posts('cat='.$cat.'&meta_key='.$meta_field.'&meta_value>=1');
I changed it to
query_posts('cat='.$cat.'&meta_key='.$meta_field.'&meta_value=1');
Use identity operator === when you want to match exact values, instead of == which checks similar values based on strings/integers.
More one this subject, check out this linkor this answer below
Using the `==` operator (*Equality*)
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2 //true, because 2 is converted to "2" and then compared
Using the `===` operator (*Identity*)
true === 1 //false
"2" === 2 // false
This is because the **equality operator == does type coercion**...meaning that the interpreter implicitly tries to convert the values and then does the comparing.
On the other hand, the **identity operator === does not do type coercion**, and so thus it does not convert the values of the values when comparing

How to omit NULL values when trying to UPDATE a table

I am fetching values from a form something like this
$value = mysql_real_escape_string($_POST['id']);
$value1 = mysql_real_escape_string($_POST['name']);
$value2 = mysql_real_escape_string($_POST['age']);
And I am using a mysql syntax like this to store information in DB
$sql = "UPDATE table SET name='$value1',age='$value2' WHERE id ='$value'";
I want the above mentioned UPDATE syntax to work only if the values are not NULL or not left blank.
For example if the name form is left blank and some value has been given for age than only age should be updated and not name..
How can I do this?
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['age']))
{
$value = mysql_real_escape_string($_POST['id']);
$value1 = mysql_real_escape_string($_POST['name']);
$value2 = mysql_real_escape_string($_POST['age']);
$sql=" UPDATE table SET name='$value1',age='$value2' WHERE id ='$value'";
}
See: isset()
At a very basic level, you could check for non-null values using isset.
For example:
if(isset($_POST['id']) && isset($_POST['name']) && isset($_POST['age'])) {
// Do the insert...
}
However, I suspect you'll probably want to carry out some proper validation to ensure that the age is valid, etc. (Perhaps via if(intval($value2) !== 0) if that makes sense.)
Also, I'd really recommend not allowing the user to arbitrarily update database records. (POSTs are very easy to spoof, and the user could simply change the form 'id' value.)
You can use empty() to check if the values are null or blank.
if ( !empty( $value) && !empty( $value1 ) && !empty( $value2 ) ) {
// Do query
}
You should also check $_POST elements using isset() to ensure the values exists before using them:
if ( isset( $_POST['id'] ) ) {
$value = mysql_real_escape_string($_POST['id']);
}
if ((isset($_POST['id']) && ($_POST['id'] !== '')) &&
(isset($_POST['name']) && ($_POST['name'] !== '')) &&
(isset($_POST['age']) && ($_POST['age'] !== ''))) {
... everything ok ... do data base stuff
} else {
die("Not correct");
}
Try this:
//$value1 = 'joey';
$value2 = 123;
$sql = "UPDATE table SET ";
$sql .= !empty($value1) ? " name='{$value1}'," : null;
$sql .= !empty($value2) ? " age='{$value2}'," : null;
$sql = substr($sql, 0, -1);
$sql .= " WHERE id ='{$value}'";
echo $sql;
It should only update the variable that is not empty. Also do the escaping like others mentioned above.

Categories