Cannot insert character into mysql column from array - php

I have following code in order to capture data from the previous page. Its working fine, the data is passing true, just the problem is the only variable that has characters ($itemName).
I simply cannot insert in mysql column. Its not type setting or character set. I suspecting its something to with a fact that the text is coming from array. Any ideas?
if(isset($_POST["cantidad"]) && count($_POST['cantidad'])>0) {
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = $_POST["cantidad"][$key];
$idItem = $_POST['hiddenField'][$key];
$itemName = $_POST['hiddenName'][$key];
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
///// this section is to check do data pass true and they do
echo "<br>";
echo "value:" . $value . "<br>";
echo "id:" . $idItem . "<br>";
echo "name:" . $itemName . "<br>";
mysql_query($query);
}
}
echo "<br>";

$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
This line is incorrect and extremely unsafe. The issue is that you are not quoting your strings in the SQL query. You need quotes around the $itemName value.
You also need to be escaping the values here. This code is wide open to SQL injection. If you use it, you will probably get hacked.
Try this:
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = mysql_real_escape_string($_POST["cantidad"][$key]);
$idItem = mysql_real_escape_string($_POST['hiddenField'][$key]);
$itemName = mysql_real_escape_string($_POST['hiddenName'][$key]);
$query = "INSERT INTO `inventarioStat` SET `fecha` = '$timestamp', `idItem` = '$idItem', `nombreItem` = '$itemName', `cantidad` = '$value'";
mysql_query($query);
}
This code is better, but not perfect. It's safer, but not 100% safe.
You should upgrade to using PDO or MySQLi and prepared statements (PDO docs or MySQLi docs).

Related

PDO Prepared Statement not returning results

I've been trying to get a proof-of-concept together all day using mysqli's prepared statements but have since decided to for PDO due to it's ability to bind values -- I believe i need them due to the dynamic nature of my queries.
The form behind the scenes is like so: http://pasteboard.co/k6H0cVq.png - You can also get an idea of the concept here. My query is returning no results or errors, just a warning Array to string conversion - which occurs when binding the values.
I am also worried that my binding of the value aren't working, i can't put them in the foreach loop as it can't be situated before the $stmt variable is called, otherwise even more errors are thrown out.
I've been reading docs and watching tutorials but i can't find anything which shows how to implement a model where the queries are dynamic.
I hope i'm clear enough, it's been a frustrating endeavour trying to get my head around PDO and prepared statements in general.
Any help is much appreciated.
Thanks!
PHP
if (isset($_POST['platform'], $_POST['bandwidth'], $_POST['price'])){
$platform = $_POST['platform'];
$bandwidth = $_POST['bandwidth'];
$price = $_POST['price'];
$query = "SELECT * FROM 'hosts' WHERE";
foreach($platform as $platform) {
$query .= " 'platform' LIKE %:platform% OR";
}
$query = substr($query, 0, -2);
foreach($bandwidth as $bandwidth) {
$query .= " AND 'bandwidth' BETWEEN :bandwidth OR";
}
$query = substr($query, 0, -2);
foreach($price as $price) {
$query .= " AND 'price' BETWEEN :price OR";
}
$query = substr($query, 0, -2);
$conn = new PDO('mysql:host=127.0.0.1; dbname=test', 'root', '');
$stmt = $conn->prepare($query);
if ($_POST['platform']){
$stmt->bindValue(':platform', $_POST['platform']);
}
if ($_POST['bandwidth']){
$stmt->bindValue(':bandwidth', $_POST['bandwidth']);
}
if ($_POST['price']){
$stmt->bindValue(':price', $_POST['price']);
}
$stmt->execute();
foreach($stmt as $row) {
print_r($row);
}
}
Here's a rewrite of your code. I use arrays to build up the nested AND and OR conditions, using implode to combine them, rather than sequences of string concatenation. I give each placeholder a different name, using the array index. I changed all your BETWEEN clauses to = because BETWEEN requires two parameters, a beginning and end of the range.
if (isset($_POST['platform'], $_POST['bandwidth'], $_POST['price'])){
$platform = $_POST['platform'];
$bandwidth = $_POST['bandwidth'];
$price = $_POST['price'];
$query = "SELECT * FROM hosts";
$ands = array();
$bind_array = array();
$ors = array();
foreach($platform as $i => $platform) {
$ors[] = "platform LIKE CONCAT('%', :platform{$i}, '%')";
$bind_array[":platform{$i}"] = $platform;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
$ors = array();
foreach($bandwidth as $i => $bandwidth) {
$ors[] = "bandwidth = :bandwidth{$i}";
$bind_array[":bandwidth{$i}"] = $bandwidth;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
$ors = array();
foreach($price as $i => $price) {
$ors[] = "price = :price{$i}";
$bind_array[":price{$i}"] = $price;
}
if ($ors) {
$ands[] = "(" . implode(" OR ", $ors) . ")";
}
if ($ands) {
$query .= " WHERE " . implode(" AND ", $ands);
}
$conn = new PDO('mysql:host=127.0.0.1; dbname=test', 'root', '');
$stmt = $conn->prepare($query);
$stmt->execute($bind_array);
foreach ($stmt as $row) {
print_r($row);
}
}
UPDATE:
If you have two parameters price1[] and price2[] for a range, change the price loop to:
foreach($price1 as $i => $price) {
$ors[] = "price BETWEEN :pricelow{$i} AND :pricehigh{$i}";
$bind_array[":pricelow{$i}"] = $price;
$bind_array[":pricehigh{$i}"] = $price2[$i];
}
I'm afraid you can't iterate over the statement as you're trying to do. Instead use the fetch method to access the results of the query:
while ($row = $stmt->fetch([fetch mode, e.g., PDO::FETCH_ASSOC])) {
print_r($row);
}
Regarding the "Array to string conversion" error you get, I suspect that one or more of the POST variables is in fact an array. To test this hypothesis, try print_r($_POST).

array from post into a single mysql row

I have an array that is built based on dynamic rows that changes every time. I am able to post the array but i get each field in a separate row. How can i insert the array into a single row.
Here is my PHP:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
$array = array();
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
}
print_r($array);
}
?>
The print array is :
Array
(
[Server_id] =>
[Server_IP_Address] => 123456789
[Server_IP2] => 123456789
[Server_Name] => Server
)
Any help is appreciated.
$table = $_POST['ItemTypeSelect'];
$isert_vals = "VALUES(";
$insert_table = "INSERT INTO `".$table."` (";
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$results = $variable;
$columnName = $key;
$array[$columnName] = $results;
$insert_table.="`".$columnName."`,";
$isert_vals.="'".$results."',";
}
}
$isert_vals = substr($isert_vals , 0 ,-1).") ";
$insert_table = substr($insert_table , 0 ,-1).") ";
$query = $insert_table.$isert_vals;
mysql_query($query);
You need to build one INSERT statement, rather than executing a new one each time you go through your loop.
Also, please note that the mysql_* functions are deprecated - you should use PDO or MySQLi instead.
Finally, you are wide open to SQL injection attacks. Use prepared statements, or all sorts of Very Bad Things will happen to your database, app, server, toaster, and dog.
Something like this should do the trick:
if (isset($_POST['item_name'])) {
$table = mysql_real_escape_string($_POST['ItemTypeSelect']);
$array = array();
$cols = array();
$vals = array();
foreach ($_POST as $key => $variable) {
$key = mysql_real_escape_string($key);
$variable = mysql_real_escape_string($variable);
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
} else {
$cols[] = $key;
$vals[] = $variable;
}
}
$columns = implode(",", $cols);
$values = implode("," , $vals);
mysql_query("INSERT INTO $table ($columns) VALUES ($values)") or die(mysql_error());
}
Be aware that mysql extension is deprecated. Consider using mysqli or PDO.
And note that you should always sanitize your database input to prevent sql-injections.

mysql not accepting apostrophe '

need help inputs are not inserted to db when there is an apostrophe in the textfield values, im trying to use the codes below to escape the ' but its not working,
function myaddslashes($string){
if(get_magic_quotes_gpc() == 1){
return $string;
} else {
return str_replace("'", "''", $string);
}
}
ive used this as well to no avail:
function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (!is_numeric($value))
{
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
here is my php code:
<?php
error_reporting(0);
require 'include/DB_Open.php';
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = $_POST['Category3'];
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];
if (isset($RemedyTicketNo))
{
$sql="INSERT into tbl_main (ars_no, phone_number, category_1, category_2, status, create_date, resolved_date, trouble_type_priority, ban_type, employee_id_name)
VALUES ('".$RemedyTicketNo."', '".$PhoneNumber."', '".$Category2."', '".$Category3."', '".$Status."', '".$Createdate."', '".$Date."', '".$Severity."', '".$BanType."', '".$XiD."')";
$result=mysql_query($sql);
header("Location: wireless_new.php");
}
?>
P.S...im new to php and sql so im still trying to learn to use sqli...
All strings should be escaped using a database-specific function. In your case mysql_real_escape_string
If you're learning, you're better off starting with MySQLi as the MySQL extension is deprecated as of PHP 5.5.0. It's no more difficult than the one you're using.
Use query parameters or whatever the php equivalent is called. Escaping quotes is one of the good things they do for you.
Mysqli will happily accept a single quote if it gets properly escaped.
but for some reason you don't actually apply none of your functions to the input. So, that's the only your problem.
Also note that error_reporting should always be E_ALL, not 0
i was able to fixed it by adding mysql_real_escape_string the field which has ' value
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = **mysql_real_escape_string** ($_POST['Category3']);
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];
if you are using
(all book's are available) as $subject and you are trying to insert in to mysql
use this
$subject=$_POST['subject'];
$disc_str = addslashes($subject);
"INSERT INTO table name (subject) value('$disc_str')";
it works for me in Textarea with tinymce also

echo json_encode() is returning NULL

I am trying to pass data to a php page via ajax, the data gets inserted to the database, then I need to pick up the last insert and pass the back to update a select menu with that last insert selected. The database gets updated correctly, but Im getting a NULL return for the echo json_echo($data);
Been stuck on this all day, would really appreciate the help!!!
if (empty($_POST) === false && empty($errors) === true) {
$company_id = $_POST['company_id'];
$patient_id = $_POST['addpatient_id'];
$first_name = $_POST['addpatient_firstname'];
$last_name = $_POST['addpatient_lastname'];
$dob = $_POST['addpatient_dob'];
$updated = $_POST['patient_added'];
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')");
$last_patient_id = mysql_insert_id();
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $last_patient_id");
$data[] = mysql_fetch_assoc($result);
}
echo json_encode( $data );
json_encode returns false if an error happened (php manual). I would start there.
$json_string = json_encode( $data );
if( $json_string ){
echo $json_string;
}else{
echo "Error";
echo "<pre>";
print_r($data);
echo "</pre>";
}
That should at least lead you a way to debug.
EDIT: Also try add this to the beginning of the function all
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will help display errors that the mysql is throwing.
EDIT: I wanted to just fix spelling, but since I need 6 characters minimum I will mention http://jsonlint.com/ to validate what you're putting into json_encode

Large Forms = Large PHP/mySql Query Strings... Is There a Good Solution?

I've got a CMS I'm building where I've got a rather large form full of data to add to my database. This is where I collect my variables....
$orgName = $_POST['orgName'];
$impact = $_POST['impact'];
$headline = $_POST['headline'];
$content = $_POST['content'];
$subContent = $_POST['subContent'];
$meterText = $_POST['meterText'];
$month = $_POST['month'];
$shopLink = $_POST['shopLink'];
$blurbTitle = $_POST['blurbTitle'];
$blurb = $_POST['blurb'];
$logoURL = $_POST['logoURL'];
$buttonURL = $_POST['buttonURL'];
$blurbURL = $_POST['blurbURL'];
$POMURL = $_POST['POMURL'];
$horizontalURL = $_POST['horizontalURL'];
$statURL = $_POST['statURL'];
$stats = $_POST['stats'];
here I sql escape, validate and send to my function (omitted validation for space)...
require_once 'DB_Connect.php';
$connection = new DB_Connect();
$connection->insertPartner(
$index,
mysql_real_escape_string($orgName),
mysql_real_escape_string($impact),
mysql_real_escape_string($headline),
mysql_real_escape_string($content),
mysql_real_escape_string($subContent),
$month,
mysql_real_escape_string($shopLink),
mysql_real_escape_string($blurbTitle),
mysql_real_escape_string($meterText),
mysql_real_escape_string($blurb),
mysql_real_escape_string($stats),
mysql_real_escape_string($logoURL),
mysql_real_escape_string($buttonURL),
mysql_real_escape_string($blurbURL),
mysql_real_escape_string($POMURL),
mysql_real_escape_string($horizontalURL),
mysql_real_escape_string($statURL)
))
and finally the function...
public function insertPartner(
$orgName = '',
$impact = '',
$headline = '',
$content = '',
$subContent = '',
$month = '',
$shopLink = '',
$blurbTitle = '',
$blurb = '',
$stats = '',
$logoURL = '',
$buttonURL = '',
$blurbURL = '',
$POMURL = '',
$horizontalURL = '',
$statURL = '')
{
$query="INSERT INTO `hupcap_FCE`.`fce_partners` (
`index`,
`organization_name`,
`impact`,
`headline`,
`content`,
`sub_content`,
`blurb_title`,
`blurb`,
`stats`,
`month`,
`meter_number`,
`meter_text`,
`shop_link`,
`button_img_url`,
`blurb_img_url`,
`logo_url`,
`month_img_url`,
`horizontal_logo_url`,
`stat_img_url`,
`util`
) VALUES (
'',
'$orgName',
'$impact',
'$headline',
'$content',
'$subContent',
'$blurbTitle',
'$blurb',
'$stats',
'$month',
0,
'',
'$shopLink',
'$buttonURL',
'$blurbURL',
'$logoURL',
'$POMURL',
'$horizontalURL',
'$statURL',
0)";
if(mysql_query($query)){
return true;
}else{
die("failed to insert record" . mysql_error());
}
}
There has GOT to be a slicker way of doing this.
Who's got the best method?
Thanks -J
Option #1
Use an ORM like Doctrine to handle CRUD in your PHP apps.
Option #2
If using an ORM is too big of a paradigm shift try something like this:
// Alias $_POST fields to SQL columns
$sql_columns= array(
'post_field1'=> 'sql_column1',
'post_field2'=> 'sql_column2',
'post_field3'=> 'sql_column3');
// Encode $_POST data for use in SQL
$sql_a= array();
foreach ($sql_columns as $k=> $k2) {
if (isset($_POST[$k])) {
$sql_a[]= sprintf("`%s` = '%s'", $k2, mysql_real_escape_string($_POST[$k]));
}
}
// Build SQL string to execute
$sql= sprintf('INSERT INTO table_name SET %s', implode(', ', $sql_a));
var_dump($sql);
This can easily be extended into a function or a class to handle different tables, columns and SQL statements.
do a foreach to run all over the params array, so you can check the value. Do some magic inside the final function so you can check if any of them is empty or something...
If you have 16 columns in your table, you're going to have a long insert statement.
You should use one of the database wrapper classes (like PDO). Firstly, it gives you a convenient way use prepared statements (avoiding SQL injection, and adding type checking). Secondly, it makes adding parameters more readable, since you don't have to concatenate one huge string.
function insert_stuff($col1, $col2, $col3) {
$conn = new PDO($connectionString);
$query = "insert into my_table (col1, col2, col3) values (:col1, :col2, :col3)";
$statement = $conn->prepare($query);
$statement->bindValue(":col1", $col1);
$statement->bindValue(":col2", $col2);
$statement->bindValue(":col3", $col3);
$statement->execute();
// etc.
}
If you're really bothered by all the typing, you can use your database to generate some of the code for you:
select
concat('$statement->bindValue(":', column_name, '", $', column_name, ');'
from
information_schema.columns
where
table_schema = 'my_database_name'
and table_name = 'my_table_name';
Something like this would work:
$insertArray() = array();
foreach ($_POST as $key=> $name)
{
$insertArray[$name] = mysql_real_escape_string($_POST[$name]);
}
$query = "INSERT INTO `hupcap_FCE`.`fce_partners` (" . implode(',', array_keys($insertArray)) VALUES '" . implode("','", $insertArray) . "'";
//...
THIS IS NOT SECURE BUT IT WOULD WORK :)
Yes it seems to be how it should be for the most part, however, you can save your life to a great extent by doing this:
Instead of writing:
$orgName = $_POST['orgName'];
$impact = $_POST['impact'];
$headline = $_POST['headline'];
$content = $_POST['content'];
$subContent = $_POST['subContent'];
$meterText = $_POST['meterText'];
$month = $_POST['month'];
$shopLink = $_POST['shopLink'];
$blurbTitle = $_POST['blurbTitle'];
$blurb = $_POST['blurb'];
$logoURL = $_POST['logoURL'];
$buttonURL = $_POST['buttonURL'];
$blurbURL = $_POST['blurbURL'];
$POMURL = $_POST['POMURL'];
$horizontalURL = $_POST['horizontalURL'];
$statURL = $_POST['statURL'];
$stats = $_POST['stats'];
You could simply write this line:
extract($_POST, EXTR_SKIP);
And now you have all the same variables available like what you did with so many lines above, for example, now you can use them or echo them:
echo $orgName;
echo $impact;
echo $headline;
To Add: I am not sure whether using extract is good practice in terms of security, however, i have been using this without any problems so far :)

Categories