php error insert data with value including addition sign (+) to database - php

There is an error while i insert "3 + 1 room" or update description area with "3 + 1 room" in MySQL database.
I saw there is no addition sign "+" in MySQL log (data inserted in database)
UPDATE testtable set status='0',title='3 1 room',
description='3 1 Daire. 1 Balkon kapalı.' WHERE id='60';
create table testtable ( id int(11), status tinyint(4), title varchar(20),
description text) ENGINE=InnoDB DEFAULT CHARSET=utf8
php file
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
$val=$baglanti->exec("UPDATE testtable set status='0',title='$title',
description='$dest' WHERE ad_no='$ad_no' ");
return $val;
What should I do?
EDIT
update.php
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
$ID=Updt($table,$fields,$values,$alan,$fvalue);
if($ID!=0){
echo $ID;
}
?>
database.php
<?php
$baglanti=new PDO("mysql:host="localhost";dbname="test";charset=utf8",$us
ername,$passwd) or die("error");
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag=$GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$val=$bag->exec("UPDATE $table set $sts WHERE $field='$fvalue'");
return $val;
}
?>
this one, programmers wrote code. I try to take question parts from all code. There were lots of codes in file.

My guess is that you are not generating the query you think you are.
This should allow you to see the query.
I have also added some error checking, that really should be used in this code.
I have amended the connection line as I am sure a newline in the middle of the $username variable will cause an error.
database.php
<?php
try {
$baglanti = new PDO("mysql:host=localhost;dbname=test;charset=utf8",
$username,$passwd);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
#UPDATE
function Updt($table,$set,$value,$field,$fvalue){
$bag = $GLOBALS['baglanti'];
$sts='';
if(is_array($set)){
for ($i=0; $i < count($set); $i++) {
$sts.=$set[$i]."='".$value[$i]."',";
}
$sts=rtrim($sts,",");
}else{
$sts=$set."='".$value."'";
}
$sql = "UPDATE $table set $sts WHERE $field='$fvalue'";
echo $sql; // you can comment this line out when you are sure the SQL is good
$val = $bag->exec($sql);
return $val;
}
?>
update.php
Small amendment here just so you know whats actually being returned from the function is a count and not a row ID. It could also be FALSE, indicating an error occured in the Updt() function in the query.
<?php
include("database.php");
$fields = array();
$values=array();
$fvalue=$_POST['id'];
$table=$_POST['table'];
foreach ($_POST as $key => $value) {
if( $key!='table' && $key!='id' && $key!='alan'){
if( strpos($key,"date")){
$datet=new DateTime($value);
$value=$datet->format('Y-m-d');
}
array_push($fields,$key);
array_push($values,$value);
}
}
$alan=$_POST['alan'];
//$ID=Updt($table,$fields,$values,$alan,$fvalue);
// this is not an ID it is a coumt of the number or rows
// updated by the Updt() function
$cnt = Updt($table,$fields,$values,$alan,$fvalue);
if ( $cnt === FALSE ) {
// then we had an error in Updt()
print_r($baglanti->errorInfo(), true);
exit;
}
if($cnt != 0){
echo 'Rows updated = ' . $cnt;
}
?>
I have to mention this as others will if I dont. Your code is open to SQL Injection you should really be using prepared statements. Maybe you should mention this to the Programmers you mentioned. Maybe you should also not assume everything they wrote was done correctly.

Related

MySQL PHP PDO : getting the table AND its size from a request

I have several functions in a PHP script :
// Database connexion
function connexion_base()
{
try
{
$bdd = new PDO('mysql:host=localhost;dbname=WORLD',
'me','S3cr3T');
}
catch (Exception $e)
{
die('Erreur : '.$e->getMessage());
}
return $bdd;
}
// Returns the names of the columns
function column_names($Table)
{
$nb_cols = $Table->columnCount();
$cols = array();
for ($i = 0; $i < $nb_cols; $i++)
{
$col = $Table->getColumnMeta($i);
$cols[] = $col['name'];
}
return $cols;
}
// Prints the body of the table
function print_table($Table,$Cols)
{
while ($datas = $Table->fetch())
{
echo '<tr>';
foreach ($Cols as $element)
{
echo '<td>'.$datas[$element].'</td>';
}
}
}
// Prints the result of request $Request (string) from database $Bdd
function print_request($Base,$Request)
{
$result = $Bdd->query($Requete);
$cols = column_names($resultat);
// Printing numer of rows of the result
// echo '<p>Number of lines in the answer : '.$nb_lignes.'</p>';
// Head of the table
echo '<table> <tr>';
foreach ($cols as $element)
{
echo '<th>'.$element.'</th>';
}
// End head of the table
// Printing each line of the table
write_table($result,$cols);
// Fin de la table
echo '</table>';
}
}
Problem(s) is(are) :
is my code correct ? It works, but maybe I didn't get the correct feeling about working with PDO (and/or PHP, MySQL...)
i'd like to add a line in the resulting page, before the table, indicating the number of results given by the request; and I don't know how to do it.
Any help ?
To add a line you can do <tr><td colspan="{$nb_cols}">{$result->rowCount()}</td></tr> after the th or after the write_table
Please watch the typos in your variables ($resultat -> $result), so that they are all the same. Php isn't case sensitive, but I would recommended to not rely on that to avoid consufusion by not mixing same variable names but with different styles.
Picky notes: please output </tr> after each loop, even though browsers are being able to find their way out

Unable to insert more than 100 rows at a time using codeigniter

I am trying to insert more than 100 records at a time. if more records them form will not perform any action unless it will submit and redirect to another page.
How to sove this error.
I tried using insert_batch also. But no use.
I changed php.ini post_max_size also,
Somebody please help me.
Below is my code for controller and model
controller code
foreach($chkproduct as $key=>$chkvalue1){
foreach($chkvalue1 as $key1=>$chkvalue2 ) {
$chkvalue=explode("/",$chkvalue2);
$datachk['product_id'] =$chkvalue[0];
$datachk['client_id']=$chkvalue[1];
$ins1=$this->Sub_model->record_count_Product($chkvalue[0]);
$num1=$ins1->num_rows();
$qry1=$ins1->row();
$prodId=$qry1->prod_rand_id;
$datachk['payment_id']=$paymentid;
$datachk['prod_rand_id']=$prodId;
$datachk['sub_type'] =$st1[$chkvalue[0]][$key1];
$datachk['prod_type'] =$pt1[$chkvalue[0]][$key1];
$datachk['quantity'] =$qty1[$chkvalue[0]][$key1];
$datachk['reductionamount'] =$redamount[$chkvalue[0]][$key1];
$datachk['amountafterreduction'] =$ramount[$chkvalue[0]][$key1];
$datachk['individual_amt'] =$ramount[$chkvalue[0]][$key1]+$redamount[$chkvalue[0]][$key1];
$cliname=$clientname[$chkvalue[0]][$key1];
//$date1=$sd1[$chkvalue];
//$datachk['start_date'] = date('Y-m-d', strtotime($date1));
$cliname=$clientname[$chkvalue[0]][$key1];
$expper=explode("-",$per1[$chkvalue[0]][$key1]);
//echo $expper[0];
$smonth=$this->check($expper[0]);
if($smonth>=10){
$startyear=$year1[$chkvalue[0]][$key1]-1;
}else{
$startyear=$year1[$chkvalue[0]][$key1];
}
//echo $st1[$chkvalue];
if($st1[$chkvalue[0]][$key1]==1){
$endyear=$year1[$chkvalue[0]][$key1];
}elseif($st1[$chkvalue[0]][$key1]==2){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+1;}else{$endyear=$year1[$chkvalue[0]][$key1];}
}elseif($st1[$chkvalue[0]][$key1]==3){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+3;}else{$endyear=$year1[$chkvalue[0]][$key1]+2;}
}
//echo $endyear;
if($smonth==01){$endmonth=12;}else{$endmonth=$smonth-01;}
$ts = strtotime($expper[0]."".$startyear);
$lastdate=date('t', $endmonth);
if($endmonth=='02'){
if($endyear%4==0){
$lastdate1=29;
}else{
$lastdate1=28;
}
}
elseif($endmonth=='04' || $endmonth=='06' || $endmonth=='09' || $endmonth=='11'){
$lastdate1=30;
}else{
$lastdate1=31;
}
//if($endmonth=='02'){$lastdate1=$lastdate-2;}elseif($endmonth%2==1){$lastdate1=30;}else{$lastdate1=31;}
$datachk['start_date'] =$startyear."-".$smonth."-01";
$datachk['end_date'] =$endyear."-".$endmonth."-".$lastdate1;
$datachk['periodicityno'] = $per1[$chkvalue[0]][$key1];
$datachk['year'] = $year1[$chkvalue[0]][$key1];
$datachk['product_status'] =$ps1[$chkvalue[0]][$key1];
if($comboval == 1 && $datachk['reductionamount']!=0){
$datachk['combostatus']=1;
}else{
$datachk['combostatus']=0;
}
$pbyp1=$this->Sub_model->getProductByperiodicity($chkvalue[0]);
$datapdf['products'][]=array("pname"=>$pbyp1->productname,"cliname"=>$cliname,"abbr"=>$pbyp1->productshortname,"pername"=>$datachk['periodicityno'],
"year"=>$datachk['year'],"subtype"=>$st1[$chkvalue[0]][$key1],"perno"=>$pbyp1->periodicity,"dur"=>$pbyp1->duration,"randid"=>$prodId,"prodid"=>$chkvalue[0]);
$this->Sub_model->addSubscribedProduct($datachk);
}
}
Model
function addSubscribedProduct($data) {
foreach ($data as $key => $value) {
if ($value=="") {
$array[$key] =0;
}else{
$array[$key] =$value;
}
}
$res = $this->db->insert('iman_subscribed_products', $array);
//$res = $this->db->insert_batch('iman_subscribed_products', $array);
//echo $sql = $this->db->last_query();
if($res) {
return 1;
} else {
return 0;
}
}
Screen shot of my form
i think you stumpled into php's max_input_vars option
the standard value for this is 1000
just change your value to something higher than that
Be aware you can't change it with ini_set.
For more information click here.
User insert_batch() instead of insert() as follows:
$this->db->insert_batch(array)); // Here the array is multidimensional which can contain number of rows as you need 100s.

How to add INSERT IGNORE INTO in Codeigniter batch insert query

How to make codeigniter function that works same as insert_batch() but generates query Like INSERT IGNORE INTO ?
I need INSERT IGNORE INTO because one of my table's key is unique and its showing error when duplicate entry comes.
I searched code for add "INSERT IGNORE INTO " instead of "INSERT INTO" in codeigniter batch insert query but I didn't found results for that.
Yes we can made our custom batch insert query by using PHP login But if you want to do it in codeigniter use this function.
Add this function in (codeigniter/system/database/DB_active.rec.php).
/*
*Function For Batch Insert using Ignore Into
*/
public function custom_insert_batch($table = '', $set = NULL)
{
if ( ! is_null($set))
{
$this->set_insert_batch($set);
}
if (count($this->ar_set) == 0)
{
if ($this->db_debug)
{
//No valid data array. Folds in cases where keys and values did not match up
return $this->display_error('db_must_use_set');
}
return FALSE;
}
if ($table == '')
{
if ( ! isset($this->ar_from[0]))
{
if ($this->db_debug)
{
return $this->display_error('db_must_set_table');
}
return FALSE;
}
$table = $this->ar_from[0];
}
// Batch this baby
for ($i = 0, $total = count($this->ar_set); $i < $total; $i = $i + 100)
{
$sql = $this->_insert_batch($this->_protect_identifiers($table, TRUE, NULL, FALSE), $this->ar_keys, array_slice($this->ar_set, $i, 100));
$sql = str_replace('INSERT INTO','INSERT IGNORE INTO',$sql);
//echo $sql;
$this->query($sql);
}
$this->_reset_write();
return TRUE;
}
To use this function
$this->db->custom_insert_batch($table_name, $batch_data);
Thanks !

Baffled as to why PHP is giving simple logic error on if statement

Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.

One roll number cant be added again [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
same roll number can not be added
I want my code to behave this way that if once i had added a roll number, it can not be added again in the registration..........same as if once an email adress is registered the error displays that EMAIL ADDRESS ALREADY BEEN TAKEN....
I am creating a function . of roll numbr value is 1 it shall display error and if not 1 it shall not display the error
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if{
$val = 1;
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
$obj_db->db_close();
}
}
?>
and the function is called at the page by this method
<?php
if(isset($_POST['btnSubmit']) and $_GET['action'] == "Add")
{
$val = $Tblstuden->selectroll($_POST['studentname'],$_POST['rollnumber']);
if ($val =='1')
{
$Tblstuden->copyPostData();
$Tblstuden->insert();
echo"asdf";
}
redirect("index.php?page=studentlist");
}
else
{
echo"abc";
}
?>
You probably want
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if ($row){
$val = 1;
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
}
?>
in line 8 of the top function - as otherwise the code won't compile.
Sub-note, your code is subject to mysql injection, you should look at using PDO (http://php.net/manual/en/book.pdo.php) for your database functions before you get used to the old method. Please. Do it now ;)

Categories