I am trying to be clever, possibly too clever in creating a set of forms that will dynamically insert their data into the database based on their input names.
I have it so it builds the query correctly, however when I attempt to insert it fails as to say it is a malformed query, is there a better way of doing what I am trying to achieve, but similarly?
<form method="post">
<input type="text" name="form_array['text']" />
<button name="insert">Go</button>
</form>
Here is my query generation, on submit of the form:
$setup['table'] = "table1";
if(isset($_POST['insert'])){
$inserts = "";
$values = "";
foreach($_POST['form_array'] as $form_id => $form_data){
if(!empty($form_data)){
if(!isset($first_run)){
$first_run = 1;
$inserts .= $form_id;
$values .= "'".$form_data."'";
} else {
$inserts .= ", ".$form_id;
$values .= ", '".$form_data."'";
}
} else {
die('error');
}
}
die("INSERT INTO '".$setup['table']."' ($inserts) VALUES ($values)");
}
Thanks.
Aside from all the fixes that was commented to you; this can be simplified, try it;
<form method="post">
<input type="text" name="form_array[column1]" />
<input type="text" name="form_array[column2]" />
<button name="insert">Go</button>
</form>
<?php
if(isset($_POST['insert'])){
$table = 'table';
$handler = 'form_array';
$keys = array_keys($_POST[$handler]);
$sql = "INSERT INTO `{$table}` (`".implode('`, `', $keys)."`) VALUES ('".implode("', '", $_POST[$handler])."')";
echo $sql;
}
Output:
INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')
Related
The HTML code is below:
<div class="form-data">
<form method="POST" action="test_upload_file.php" enctype="multipart/form-data">
ID:<br>
<input type="text" name="id"><br>
Quote:<br>
<textarea rows="4" cols="30" name="text-file"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
The corresponding php code is below:
<?php
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$text = $_POST['text-file'];
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$text')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}
?>
I want to post multiple sentences separated by break in textarea. They should be stored in different rows in MySQL database.
For eg, if i put an id of 2 and post a text having multiple sentences separated by break or newline, then it should store in the database like this:
quote_id quote
2 line 1
2 line 2
2 line 3
Try following code, it may help you. I am not sure the textarea next line seperated by '\n'. Please make sure that
//connect database
$conn = mysqli_connect("localhost","root","","androidtest");
if (isset($_POST['submit'])) {
$quote_id = $_POST['id'];
$get_file = $_POST['text-file'];
$textArray = explode("\n", $get_file);
foreach($textArray as $key=>$value) {
//insert data
$sql = "INSERT INTO quotes (quote_id, quote) VALUES ('$quote_id', '$value')";
//store in the table
$insert = mysqli_query($conn, $sql);
if ($insert) {
echo "Success.";
} else {
echo "Error.";
}
}
//close mysql connection
mysql_close($conn);
//won't resubmit the form
header("Location: " . $_SERVER['REQUEST_URI']);
}
I'm trying to introduce the value of a checkbox into my database in postgresql. I created the table account with a colum named: getrequest which is the type boolean.
I'm using the code below, but I'm getting the following error:
Error with query: ERROR: invalid input syntax for type boolean: "" LINE 1: ...account(getrequest) VALUES('', ... ^
Any help would be highly appreciated.
Thanks
<?php
$getrequest = "";
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$getrequest = pg_escape_string($_POST['getrequest']);
$query = "INSERT INTO account(getrequest) VALUES('" . $getrequest . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
$getrequest = "";
pg_close();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="checkbox" name="getrequest" value="getrequest" class="regular-checkbox">I get a request<br>
<br>
<input type="submit" name="submit" value="SAVE">
</form>
Verify that the value you are trying to insert is a valid boolean value ( http://www.postgresql.org/docs/9.1/static/datatype-boolean.html ), before inserting, and convert it if needed.
Matbe filter_var($getrequest, FILTER_VALIDATE_BOOLEAN)?'true':'false';
Also, you don't quote boolean or numeric types, Reomove the quotes from your insert statement:
INSERT INTO account(getrequest) VALUES(' . $getrequest . ')'
I was wondering if you could help me with a problem when submitting a form to POST values and using a PDO Insert function to enter values into database. Once someone can help me find the issue I will be able to use code over again in form areas. I have checked my $conn PDO statement and it is connected correctly to database just I can not insert the data from form.
My coding layout:
Form located in cust_form.php, names of form fields are as in database with the exception of an autoID generated upon insertion.
Class.php is used to take POST values and to send to Insert function located in db.php.
db.php
<?php
//dbdt database class
if(!class_exists('dbdt')){
class dbdt {
//Connect and select database
function connect() {
try {
require_once('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends', $DB_USER, $DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Connect to above
function __construct() {
$this->connect();
}
//Insert data into database
function insert($conn, $table, $fields, $values) {
try{
$fields = implode(", ", $fields);
$values = implode(", ", $values);
$insert = "INSERT INTO $table (autoID, $fields) VALUES ('', $values)";
$query = $handler->prepare($insert);
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
}
}
$dbdt = new dbdt;
?>
class.php
<?php
if(!class_exists('cust_form')){
class cust_form {
/*
CUSTOMER FORM = cust_form.php
*/
function cust_upd_cre_del(){
if ( isset( $_POST['cust_upd'] ) ) {
$int_custID=$_POST['int_custID'];
$cust_company=$_POST['cust_company'];
$cust_address=$_POST['cust_address'];
$cust_postcode=$_POST['cust_postcode'];
$cust_contact_1=$_POST['cust_contact_1'];
$cust_contact_2=$_POST['cust_contact_2'];
$cust_tel=$_POST['cust_tel'];
$cust_mob=$_POST['cust_mob'];
$cust_DDI=$_POST['cust_DDI'];
$cust_email=$_POST['cust_email'];
$cust_notes=$_POST['cust_notes'];
require_once('db.php');
$table = 'customers';
$fields = array(
'int_custID',
'cust_company',
'cust_address',
'cust_postcode',
'cust_contact_1',
'cust_contact_2',
'cust_tel',
'cust_mob',
'cust_DDI',
'cust_email',
'cust_notes'
);
$values = array (
'int_custID' => $int_custID,
'cust_company' => $cust_company,
'cust_address' => $cust_address,
'cust_postcode' => $cust_postcode,
'cust_contact_1' => $cust_contact_1,
'cust_contact_2' => $cust_contact_2,
'cust_tel' => $cust_tel,
'cust_mob' => $cust_mob,
'cust_DDI' => $cust_DDI,
'cust_email' => $cust_email,
'cust_notes' => $cust_notes
);
$insert = $dbdt->insert($conn, $table, $fields, $values);
if ( $insert == TRUE ) {
}
} else {
die('Your form was not submitted.');
}
}
}
}
$cust_form = new cust_form;
?>
cust_form.php
<!doctype html>
<?php
require_once('load.php');
?>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Form</title>
</head>
<body>
<form action="" method="POST" name="cust_details_form" id="cust_details_form">
<label>Account No:</label>
<input type="text" name="int_custID" id="int_custID" />
<label>Company:</label>
<input type="text" name="cust_company" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 name="cust_address" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" name="cust_postcode" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" name="cust_contact_1" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" name="cust_contact_2" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" name="cust_tel" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" name="cust_mob" id="cust_mob"/>
<label>DDI:</label>
<input type="text" name="cust_DDI" id="cust_DDI"/>
<label>Email:</label>
<input type="email" name="cust_email" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 name="cust_notes" id="cust_notes"></textarea>
<input type="submit" name="cust_upd" id="cust_upd" value="Update">
<input type="submit" name="cust_del" id="cust_del" value="Delete">
</form>
</body>
</html>
load.php contains require_once db.php, class.php & config.php (contains username and password). This file is okay.
Thanks for any help you may be able to give!
EDITTED
Thanks for all your help! Here is the working code for anyone who needs it!
function ins_upd($table, $values) {
try{
include('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', $DB_USER, $DB_PASS);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip $_POST array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
You don't need to send "fields" parameters because if that array is in a different order than "values" your code won't work. Use the array keys from "values":
//Insert data into database
function insert($conn, $table, $values) {
try {
$keys = array_keys($values);
$fields = implode(", ", $keys);
$values = ":" . implode(", :", $keys);
$insert = "INSERT INTO $table ($fields) VALUES ($values)";
$query = $handler->prepare($insert);
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
Hope it helps. I couldn't test it without complete code.
PS: Avoid using prepare to execute SQL statements without using bindParam because you must to quote strings but not integers or floating point numbers.
I have this page of html
<html>
<body>
<form action="new_group.php" method="post">
<div>
<label for="group_name">Group Name: </label>
<input type="text" name="group_name" id="group_name" />
</div>
<div>
<label for="invites">Invite...</label>
<input type="text" name="invites" id="invites" />
</div>
<div>
<label for="description">Description: </label>
<textarea name="description" id="description"></textarea>
</div>
<div>
<input type="submit" value="Create" />
</div>
</form>
</body>
</html>
Which then has this PHP:
<?php
include "function_inc.php";
if(isset($_POST['group_name'], $_POST['description'], $_POST['invites'])){
$invites = explode(',', $_POST['invites']);
$user_id = $_SESSION['user_id']; //avoids issues with quotations (either invalid quotation for referring to PHP variable or repeated double quotes)
$result = mysqli_query($link, "SELECT `username` FROM `users` WHERE `user_id` = '$user_id'");
foreach($result as $resul){
foreach($resul as $resu){
$logged_in_username = $resu;
}}
if(in_array($logged_in_username, $invites)){
}else{
$invites[] = $logged_in_username;
}
foreach($invites as $invite) {
$invite = trim($invite);
echo $invite . '<br />';
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
if(mysqli_num_rows($idres) == 0) {
exit("1 or more of the users that you entered do(es) not exist!");
}
}
create_group($_POST['group_name'], $_POST['description'], $invites);
}
?>
and this is the create_group function:
function create_group($name, $description, $invites){
global $link;
$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");
$descriptions = mysqli_query($link, "SELECT `group_description` FROM `groups` WHERE `group_description` = '$description'");
if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0) {
mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
} else {
echo 'Group with that name/description already exists.';
}
$result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");
foreach($result as $resul) {
foreach($resul as $resu) {
$group_id = $resu;
}
}
foreach($invites as $invite) {
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
foreach($idres as $idarr) {
foreach($idarr as $id) {
mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
}
}
}
echo 'Group created!';
}
What I am confused about is the following: if I create a group (for testing purposes) and include my (the current user logged on's) name, and have commas but no spaces in between, everything works fine. However, if I do the exact same thing, however I have spaces, only the first name in the array enters group_members. As you can see, there is a trim statement.
I have no idea why this is. Any help would be much appreciated as I am a beginner at PHP.
Thank you in advance
In the code:
foreach ($invites as $invite) {
$invite = trim($invite);
...
}
The variable $invite is separate from the array element. Assigning to that variable does not modify the contents of the array. You can fix this by using a reference:
foreach ($invites as &$invite) {
$invite = trim($invite);
...
}
The & prefix makes $invite a reference variable, i.e. an alias for the array element. Now, assigning to the variable updates the array element that it refers to.
I'm trying to use the code below for a comment system. It doesn't work. The info I'm trying to insert into the MySQL table "comment" isn't getting put there. Any idea(s) why it is not working?
Thanks in advance,
John
On comments.php:
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
On comments2.php:
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
mysql_query("INSERT INTO comment VALUES (NULL, '$uid', '$subid', '$comment', NULL, NULL)");
try
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);
If mysql_query() fails it returns false and mysql_error() can tell you why.
Also take a look at http://docs.php.net/security.database.sql-injection and either use mysql_real_escape_string() or prepared statements.
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
$rc=mysql_query($query, $mysql);
if ( !$rc ) {
die( htmlspecialchars(mysql_error()) );
}
Try this self-contained example (only an example, don't code it this way ;-))
<?php
session_start();
if ( !isset($_SESSION['loginid']) ) {
login();
}
else if ( !isset($_POST['comment']) ) {
showForm();
}
else {
saveComment();
}
function saveComment() {
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
// insert correct values here:
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
//$rc=mysql_query($query, $mysql);
//if ( !$rc ) {
//die( htmlspecialchars(mysql_error()) );
//}
}
function login() {
$_SESSION['loginid'] = rand(1, 100);
echo 'Your new loginid is ', $_SESSION['loginid'],'<br />
Continue
';
}
function showForm() {
$submissionid = rand(1000, 9999);
echo '<div>submissionid=', $submissionid, '</div>';
echo '<div>loginid=', $_SESSION['loginid'], '</div>';
echo '<form action="?" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
if this "works" compare it to your real application and find the (essential) differences.
Valid return values from yourform
Does
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
contain valid data?
SQL query valid
http://www.w3schools.com/sql/sql_insert.asp
What does mysql_query return
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
what mysql_error do you get for your query.
Use PDO instead of mysql_query()
I would advise you to have a look at PDO which does a lot of heavy lifting for you. It for example makes sure that your SQL query is safe because even if the comments was added to your database it could(would) not be safe at all.
PHP security
You should always validate your users input to prevent SQL injection. Luckily when using PDO(using prepared statements which will also give you a speed boost)right this will be done for you behind the seens. Still I would advise you to read these quick security tips from PHP creator to secure your site.
Hopefully this tips will help you in any way.
You need the field names for any INSERT statement. As I don't know the exact ones for your table, I'll make some guesses.
mysql_query("INSERT INTO comment(uid,subid,comment) VALUES($uid, $subid, $comment)");