Number not getting added in mysql database format ( number - number ) - php

I need to add data in my database and one way or the other the format must be like,
0 - 0 or 1 - 5
i have tryed =>
mysqli_real_escape_string();
but did not work.
i have also tryed changing the sign to / , * , +, exp.
PHP
$dataBase->_insertDataBase('tableNaam', $input);
function _insertDataBase($tabel,$input){
$velden='';
$waarden='';
$i=0;
foreach($input AS $key=>$value){
$i=$i+1;
if($i !== count($input)){
$a=', ';
}else{
$a='';
}
$velden.=$key.$a;
$waarden.=$value.$a;
unset($a);
}
$sql = "INSERT INTO `$tabel`($velden) VALUES ($waarden)";
$this->_conn()->query($sql);
}

The problem is your SQL statement is giving the equation 5-1 as a value, so the server is doing the math and inserting 4 just like you told it to. You need tell it that it's a literal string by surrounding the values with apostrophe's (i.e. '5-1').
Replace:
foreach ($input AS $key => $value) {
$i = $i + 1;
if ($i !== count($input)) {
$a = ', ';
} else {
$a = '';
}
$velden .= $key . $a;
$waarden .= $value . $a;
unset($a);
}
With:
$velden = array();
$waarden = array();
foreach ($input AS $key => $value) {
$velden[] = $key;
$waarden[] = $value;
}
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";
Or possibly even:
$velden = array_keys($input);
$waarden = array_values($input);
$velden = implode(',', $velden);
$waarden = "'" . implode("','", $waarden) . "'";

Related

Type conversion failing after dynamically constructing INSERT statement?

I am attempting to dynamically create an INSERT statement based on JSON key/value pairs where the $key is the database field of string or integer data type and $value is an integer or string. I haven't had issues inserting numeric strings into Postgres before but it is failing.
Example:
$json = '{"stringField":"string","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value != NULL) {
$columns .= $key . ', ';
$values .= "'" . $value . "', ";
}
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');
This is cleaner PHP:
$json = '{"stringField":"string","numberField":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value !== NULL) {
$columns .= $key . ', ';
$values .= is_numeric($value) ? $value : "'" . $value . "', ";
}
}
$query = 'INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');';
Please think about escaping your values.
The issue turned out to be that one of the values was actually a float numeric string failing on insert into an integer field, rounding the value if it is a numeric string solves this. The is_numeric check avoids string fields being converted to 0.
Solution:
$json = '{"stringField":"string","floatString":"42.0","intString":"42"}';
$columns = $values = '';
foreach (json_decode($json, true) as $key => $value) {
if ($value != NULL) {
$columns .= $key . ', ';
$values .= is_numeric($value) ? round($value) . "," : "'" . $value . "', ";
}
}
$query = ('INSERT INTO table ('.rtrim($columns, ', ').') VALUES ('.trim($values, ', ').');');

Using Foreach loop for inserting data into 70 fields long database

I have 70 text fields in my HTML form. I want to insert data from those fields to the database using php and mysqli. So I thought of using the foreach loop while creating the sql query..I tried the following, but I am not able to get the required result.
foreach ($_POST as $key => $value) {
$f = $f . "," . $key ;
$v = $v . ",'" . $value . "'";
}
$sql = "insert into table1($f) values ($v)";
The variablefis supposed to carry a string of comma seperated field names which are fields of the $_POST array. While variable v is to carry single quoted comma seperated values of the $_POST array. I am getting an extra comma in the starting of f and v right now. How to remove that.
Please help!
you should use rtrim() to remove that extra commas from the right side
foreach ($_POST as $key => $value) {
$f = $f . "," . $key ;
$v = $v . ",'" . $value . "'";
}
$f = rtrim($f,',');
$v = rtrim($v,',');
$sql = "insert into table1($f) values ($v)";
rtrim($f, ",") would cut trailing commas.
trim($f, ",") would cut trailing and prefixing commas.
you can also use substr() to remove last character from string like below
substr($f, 0, -1);
substr($v, 0, -1);
further reading for
trim() : http://php.net/trim
rtrim() : http://php.net/rtrim
substr() : http://php.net/substr
EDIT
A better way would be
$f = array(); // create blank arrays
$v = array();
foreach ($_POST as $key => $value)
{
$f[] = $key; // push values to the array
$v[] = $value;
}
$f1 = implode(",", $f); // convert array to comma separated string
$v1 = implode(",", $v);
$sql = "insert into table1($f1) values ($v1)";
let me know if that helped you..
Try this
foreach ($_POST as $key => $value) {
$f .= $f . "," . $key ;
$v .= $v . ",'" . $value . "'";
}
$f = ltrim($f,',');
$v = ltrim($v,',');
$sql = "insert into table1($f) values ($v)";
Better to check first using isset() before prefixing comma, this will also remove the warnings you are getting.
foreach($_POST as $key => $value) {
$f = isset($f) ? $f . "," . $key : $key;
$v = isset($v) ? $v . "," . $value : $value;
}

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

PHP - Looping through a QueryString

Trying to loop through a querystring in php but only getting last value. What should I be doing to get all values?
example:
querystring = ?style=ranch&style=barn&style=colonial
php:
$sqlStyle = "SELECT DISTINCT COUNT(*) as count FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
$sqlStyle .= $key . " like '%" . $value ."%'";
$i++;
}
echo $sqlStyle;
Result:
SELECT DISTINCT COUNT(*) as count FROM houses_single Where Houses like '%colonial%'
The query parameter "style" is an array in this case and must be identified by square brackets - if not, the last key=value pair will overwrite the others.
?style[]=ranch&style[]=barn&style[]=colonial
$_GET['style'] is an array then you can loop over by using foreach:
foreach ($_GET['style'] as $value) {
// ...
}
if 'style' is not the only parameter you want to add, you can use a is_array() check in the foreach loop:
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
if(is_array($value)) {
$sec = array();
foreach($value as $second_level) {
$sec[] = $key . " LIKE '%" . $second_level."%'";
}
$sqlStyle .= implode(' AND ', $sec);
}
else {
$sqlStyle .= $key . " LIKE '%" . $value ."%'";
}
$i++;
}
echo $sqlStyle;
alternative without foreach:
<?php
$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
if(is_array($_GET)) {
$statement .= ' WHERE';
// create copy to keep the $_GET array
$add_where = $_GET;
array_walk(function($elem,$key){
is_array($elem) {
return implode(' AND ', array_map(function($sec) using ($key) {
return "$key LIKE '%$sec%'";
}, $elem);
}
else {
return "$key LIKE '%$elem%'";
}
},$add_where);
$statement .= implode(' AND ', $add_where);
}
(codes are untested)
Sidenode about safety: I hope you won't use this code snippet you provided in productive environment without any escaping of the parameters.

writing out checkbox list to string array for json php

I want to be able to write is a string that is an array which is going to be stored in a jason string in a data base. My code iterates over the checkboxes but I want to be able todo is test if the $input name is "interests"
<input type="checkbox" name="interests[]" value="dvd" />` <-- checkbox lists
the other thing which I can't get is to put quotes around each $value like e.g "dvd", "computers"
$interests = '[';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
if(is_array($input)) {
// test here is input is "interests"
foreach($input as $index => $value) {
$interests .= /*quote here*/ $value /*quote here*/ .= ($count < $counter) ? ',' : '';
$count += 1;
}
}
}
$interests .= ']';
echo $interests;
interests is suppose to write out ["dvd", "computers", "hard drives"]
but it only writes out [dvd, computers, hard drives]
$_POST["interests"] = array("dvd", "computers", "hard drives");
$interests = '["' . implode('","', $_POST["interests"]) . '"]';
echo $interests;
See it in action
Use json_encode() instead of manually creating the JSON:
echo json_encode($_POST['interests']);
Outputs
["dvd","tv","radio"]
Try this,
$interests = '';
$count = 1;
$counter = count($_POST["interests"]);
foreach($_POST as $checkbox => $input) {
if(is_array($input)) {
// test here is input is "interests"
foreach($input as $index => $value) {
$interests .= $value .= ($count < $counter) ? ',' : '';
$count += 1;
}
}
}
$interests = json_encode($interests);
echo $interests;

Categories