Can't save $_POST array to database with function - php

I have a form that has multiple inputs of the same name, resulting in an array. I want to pass this $_POST array to a function which will process and save the array into a database.
I've done this before with no problems without using a function, but now that I want to contain it all in a nice neat function call it won't do it and I'm not sure why?
The input/post variable in question is named option[] and is passed to the function as $_POST['option']. Here is the function:
function newVariant($name, $option) {
global $db;
global $table_prefix;
$table = $table_prefix . "variants";
$query = $db->prepare("INSERT INTO $table(name) VALUES(:name)");
$query->bindParam(":name", $name);
if (!$query->execute()) {
die(showMessage("Error!","There has been a problem saving your variant. Please try again or contact technical support if the problem persists.",""));
}
$variant_id = $db->lastInsertId('id');
for($i = 0; $i < count($option); $i++) {
if($option[$i] != "") {
$table2 = $table_prefix . "variant_items";
$query2 = $db->prepare("INSERT INTO $table2(variant, option) VALUES(:variant, :option)");
$query2->bindParam(":variant", $variant_id);
$query2->bindParam(":option", $option[$i]);
if (!$query2->execute()) {
die(showMessage("Error!","There has been a problem saving your variant. Please try again or contact technical support if the problem persists.",""));
}
}
}
$redirect = renderLink("/beyond/?act=admin&sub=variants", "true");
showMessage("Saving variant...<META HTTP-EQUIV=\"Refresh\" Content=\"1; URL=$redirect\">","","");
}
This is the error I'm getting in my log:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'option) VALUES(?, ?)' at line 1' in /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php:131
Stack trace:
#0 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php(131): PDO->prepare('INSERT INTO bb_...')
#1 /Users/adampcollings/Sites/Hot Mint Development/beyond/html/admin/new-variant.php(5): newVariant('Test', Array)
#2 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/html.php(19): include('/Users/adampcol...')
#3 /Users/adampcollings/Sites/Hot Mint Development/beyond/html/admin.php(10): subElement('admin', 'new-variant')
#4 /Users/adampcollings/Sites/Hot Mint Development/beyond/php/html.php(8): include('/Users/adampcol...')
#5 /Users/adampcollings/Sites/Hot Mint Development/beyond/index.php(14): siteElement('a in /Users/adampcollings/Sites/Hot Mint Development/beyond/php/functions/product.php on line 131

Based on the comment thread above, there are several things you should try.
First, always enable error reporting when debugging an application. To do this in your script, add:
error_reporting(E_ALL);
to the top of your script.
Second, ensure that $options contains the data you expect. Somewhere in your code, add the following line:
var_dump($options);
This will show you the contents of $options. If it does not contain the values you expect, check your submission process.
Finally, if $options contains the expected data, check your table structure to ensure that your query matches and inserts the correct values.
EDIT: After you posted the MySQL error, I cross-checked the MySQL Reserved Words list. The word 'option' is on the list. As such, the query is failing because the word is not recognized as a column name. Try surrounding the column name with backticks:
$query2 = $db->prepare("INSERT INTO $table2(`variant`, `option`)...

Related

php stored procedure adding error

I want to add data to my table with stored procedure, but I have this error:
Gönder
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Teknoloji,V,,1)' at line 1' in C:\xampp\htdocs\berat\isyerikayit.php:142 Stack trace: #0 C:\xampp\htdocs\berat\isyerikayit.php(142): PDO->query('CALL isyerikayi...', 2) #1 {main} thrown in C:\xampp\htdocs\berat\isyerikayit.php on line 142
<?php
if (isset($_POST['gonder']))
{
$adi = $_POST["adi"];
$calismaturu = $_POST["calismaturu"];
$iscigucu = $_POST["iscigucu"];
$hizmetturu = $_POST["hizmetturu"];
$butce = $_POST["butce"];
if($calismaturu == 'V')
{
$sorgu= $db->query("CALL isyerikayitV($adi,$calismaturu,$iscigucu,$hizmetturu)",PDO::FETCH_ASSOC);
echo '<script>alert("Hizmet Veren Firma Eklendi.");</script>';
}
else
{
$sorgu= $db->query("CALL isyerikayitE($adi,$calismaturu,$butce)",PDO::FETCH_ASSOC);
echo '<script>alert("Hizmet Edilen Firma Eklendi.");</script>';
}
}
?>
My isyerikayitE() and isyerikayitV procedures are 7.
It seems that $iscigucu is empty:
"that corresponds to your MariaDB server version for the right syntax to use near 'Teknoloji,V,,1)'"
And all your string variables are missing the quotes:
A quick solution is to do:
$iscigucu = empty($_POST["iscigucu"]) ? "''" : "'".$_POST["iscigucu"]."'";
for each one of them.
or
$iscigucu = "'".$iscigucu."'"
But the right way to solve this is to use prepared statements:
$call = mysqli_prepare($mysqli, 'CALL test_proc(?, ?, ?, ?)');
mysqli_stmt_bind_param($call, 'ssss', $adi,$calismaturu,$iscigucu,$hizmetturu);
mysqli_stmt_execute($call);
Take a look at: http://php.net/manual/en/mysqli-stmt.bind-param.php

Using prepared statements but quotes not being escaped or removed

I am having an issue getting some things to insert into my database. If I put quotes single or double into my text fields it will break the query and will not escape them. I just got done reading that using prepared statements eliminates the need to call mysql_real_escape_string. Can someone tell me if I am executing my query wrong. $companyInfo is an array that contains about 8 rows to be inserted.
function InsertCompanyInfo($companyInfo, $conn) {
foreach($companyInfo as $key => $table) {
$keys = array_keys($table);
$values = null;
$x = 1;
foreach($table as $row => $value) {
$values .= "'$value'";
if($x < count($keys)) {
$values .= ', ';
}
$x++;
}
$sql = $conn->prepare("INSERT INTO {$key} (`" . implode('`, `', $keys) . "`) VALUES ({$values});");
$sql->execute();
$CompanyID = $conn->lastInsertId('CompanyID');
}
return $CompanyID;
}
This is the error I get when I insert qoutes:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax
error or access violation: 1064 You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near '1',
''''"'"''"';;''';';')' at line 1' in /var/www/Survey/InsertFunctions.php:20 Stack trace: #0
/var/www/Survey/InsertFunctions.php(20): PDOStatement->execute() #1
/var/www/Survey/testProcess.php(8): InsertCompanyInfo(Array, Object(PDO)) #2 {main} thrown
in /var/www/Survey/InsertFunctions.php on line 20
Prepared statements work by separating the query structure and the values in code like so:
$stmt = $pdo->prepare('INSERT INTO foo (bar) VALUES (?)');
This is the query structure, which the database is given first to understand. Then you give it the values separately:
$stmt->execute(array('baz'));
What you're doing instead is you call prepare on a completely formed query which includes crudely interpolated values. There's nothing prepare can do here. The entire problem of escaping values is that the database cannot figure out what a value was and what your part of the query was after the fact. If you're giving the query fully formed and incorrectly escaped to the database, it can't magically recognise what was supposed to be what. You need to add placeholders to the query and provide the corresponding values in a separate step.

unexpected error on inserting values and error with implode()

I am inserting the values using PDO but i am getting error as:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,u' at line 1' in C:\wamp\www\aa\abc.php:58 Stack trace: #0 C:\wamp\www\www\aa\abc.phpphp(58): PDOStatement->execute(Array) #1 {main} thrown in C:\wamp\www\www\aa\abc.php.php on line 58
also getting Warning: implode() [function.implode]: Bad arguments for implode function
Code:
foreach ($_POST['pcheck'] as $p_check) ////storing checkbox values
{
$pcheckp[] = $p_check;
} $finalcheck = implode(',', $pcheck);
foreach ($_POST['pinc'] as $p_inc) ////storing inputfield values
{
$pinc[] = $p_inc;
} $finalpinc = implode(',', $pinc);
$sql = "INSERT INTO list (u_id,list_type,list_ff,breed,title,desc,price,nick_name,gender,size,color,birth_date,uname,uphone,ucountry,ustate,ucity,usite,pcheck,pinc,photo)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";
$q = $db->prepare($sql);
$q->execute(array(':uid'=>dd,
':list_type'=>$list_type,
':breed'=>$breed,
':title'=>$title,
':desc'=>$desc,
':price'=>$price,
':list_ff'=>$list_ff,
':nick_name'=>$nick_name,
':gender'=>$gender,
':size'=>$size,
':color'=>$color,
':date'=>$date,
':uname'=>$uname,
':uphone'=>$uphone,
':ucountry'=>$ucountry,
':ustate'=>$ustate,
':ucity'=>$ucity,
':usite'=>$usite,
':pcheck'=>$finalcheck,
':pinc'=>$finalpinc,
':p_photo'=>$p_photo));
$_POST['pcheck'] and $_POST['pinc'] is used to get checkbox and input values which i am going to store in column in mysql.
I have checked many times to find the syntax error in insert query but nothing wrong is in it
Hoping to get help
Thanks!
for Warning: implode()
$finalcheck = implode(',', $pcheck);
should be
$finalcheck = implode(',', $pcheckp);
also desc is reserved for mysql you need to use it with `
$sql = "INSERT INTO list (`u_id`,`list_type`,`list_ff`,`breed`,`title`,`desc`,`price`,`nick_name`,`gender`,`size`,`color`,`birth_date`,`uname`,`uphone`,`ucountry`,`ustate`,`ucity`,`usite`,`pcheck`,`pinc`,`photo`)
VALUES(:uid,:list_type,:list_ff,:breed,:title,:desc,:price,:nick_name,:gender,:size,:color,:date,:uname,:uphone,:ucountry,:ustate,:ucity,:usite,:pcheck,:pinc,:p_photo)";

Changing php script to PDO causing Syntax error during MySQL update query

I have a php script to update details in a MySQL table. It all worked fine but now I have changed the db connection method to PDO:
$pdo = new PDO('mysql:host=localhost;dbname=****', '****', '*****');
I made various changes to the script to accommodate this so it continues to work, The only place that fails is right at the end after the mysql table has been updated. I get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'and park_id=31' at line 1' in /home3/danville/public_html/test2/index.php:29 Stack trace: #0 /home3/danville/public_html/test2/index.php(29): PDO->query('update tpf_ride...') #1 {main} thrown in /home3/danville/public_html/test2/index.php on line 29
This is the piece of code causing the error:
$query = "update tpf_rides set name='$name',type='$type'";
if($topride!=""){$query .= ",top_ride=$topride";}
if($info!=""){$query .= ",info='$info'";}
if($height!=""){$query .= ",height=$height";}
if($length!=""){$query .= ",length=$length";}
if($speed!=""){$query .= ",speed=$speed";}
if($inversions!=""){$query .= ",inversions=$inversions";}
$query .= " where ride_id=".$ride_id." and park_id=".$park_id;
$pdo->query($query);
}
line 29 is this on Notepad++ $pdo->query($query); although the error message seems to reference the line above that $query .= " where ride_id=".$ride_id." and park_id=".$park_id;
Any ideas what I ned to change to stop the error? Additional details - I connect to the db with a require_once include. The updates do take effect despite the error.
If you're going to switch to PDO, you might as well take advantage of prepared statements and parameter binding. It actually makes your queries much safer from SQL injection and also makes your code more readable. Your query builder approach does complicate things a little but it's still possible. I'd also highly recommend enabling error reporting during development. For example
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$upd = array('name = :name', 'type = :type');
$values = array(
'name' => $name,
'type' => $type,
'ride_id' => $ride_id,
'park_id' => $park_id
);
if (!empty($topride)) {
$upd[] = 'top_ride = :topride'; // :topride is the named parameter placeholder
$values['topride'] = $topride; // the array key matches the named placeholder above
}
if (!empty($info)) {
$upd[] = 'info = :info';
$values['info'] = $info;
}
// and so on
$query = sprintf('UPDATE tpf_rides SET %s WHERE ride_id = :ride_id AND park_id = :park_id',
implode(', ', $upd));
$stmt = $pdo->prepare($query);
$stmt->execute($values);

Can't Read static::$table_name after looping [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I get the following error messages:
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in /home/u522148874/public_html/includes/database-objects.php on line 27
Sample 1
Sample 2
When using the following code:
public function __construct(){
global $MySQLDatabase;
global $news;
$this->dbh = $MySQLDatabase->open_connection();
// Convert Table Fields in to Attributes
static::$db_fields = $this->get_dbFields(static::$table_name);
foreach(static::$db_fields as $field){
$this->$field = "";
}
}
// Get Table Fields from the Database
public function get_dbFields($table_name){
$sql = 'DESCRIBE ' . $table_name ;
$query = $this->dbh->prepare($sql);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_OBJ);
// Get the quantity of the Table Columns
$count = count($result);
$field = array();
// Loop through each column to get the 'Field'
// ($count - 1) -> $count is minus 1 because array count starts with zero
// Example : Table Have 8 Columns
// $count will read it as 1 - 8 while array ($result[i]) reads it as 0 - 7
for($i = 0; $i <= ($count - 1); $i++){
$field[] = $result[$i]->Field;
}
return $field;
}
Can anyone explain to me why I am having those errors above but still can get the output (Sample 1 and Sample 2) above?
Here is my Complete Code: http://pastebin.com/xypkzs30
The problem is in the method DatabaseObjects::instantiate. The first line says
$object = new self;
Now, self is a reference to the current class, that means the class in which the instantiate-method is implemented (DatabaseObjects) and not the class on which it is called.
So you don't create new News objects where the table_name is defined but DatabaseObjects objects which have no table_name defined.
You can resolve this by creating new instances using the "late static binding"-version:
$object = new static;
That way the method creates new News objects. You might want to also mark the DatabaseObjects class as abstract, so no accidental instantiation occurs.
Plus you might want to globally cache the get_dbFields method - otherwise you hit the DB for every instantiation of the News class (your users might fall asleep using your app).

Categories