Inser checkbox inputs into a postgresql with php - php

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 . ')'

Related

storing text in different rows of MySQL database based on newline

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']);
}

PHP Dynamic Query Creation from form

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')

POST empty fields result in query error

I have a form with some fields
<form action="add.php" method="post">
/*Some fields*/
</form>
Also I created the following function to quote and escape form submitted values
<?php
// Quote and escape form submitted values
function db_quote($value) {
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>
Then I pass values to the function as following
$inventoryId = db_quote($_POST['inventoryId']);
$sn = db_quote($_POST['sn']);
$model = db_quote($_POST['model']);
//etc...
Every thing work fine if I fill all the fields, but if there is at least one empty filed i.e. no value entered by the user I get the following error
Catchable fatal error: Object of class mysqli could not be converted to string in etc...
Here is the query I am trying to run
<?php
$sql = "INSERT INTO inventory (id,manufacturer_id,supplier_id,servicer_id,operator_id,sn,model,inventory_name,inventory_type,description,power,purchase_order,purchase_cost,arrival_date,installation_date,warranty_date,incident_history,conditions,m_next_date,m_start_date,m_deadline,lifetime,inspection_frequency,location,purchased_from)
VALUES ($inventoryId,$manufacturer,$supplier,$servicesId,$operatorId,$sn,$model,$inventoryName,$inventorType,$description,$power,$purchaseOrder,$purchaseCost,$arrivalDate,$installationDate,$warranty,$incident,$conditions,$nextDate,$startDate,$deadline,$lifetime,$inspection,$location,$purchasedFrom);";
if ($connection->query($sql) === TRUE) {
echo "<p>New inventory ".$inventoryId." created successfully</p>";
} else {
echo "Error: " . $sql . "<br>" . $connection;
}
$connection->close();
?>
Update: The issue only with Auto Increment columns
<?php
// Quote and escape form submitted values
function db_quote($value) {
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>
Convert it to
<?php
// Quote and escape form submitted values
function db_quote($value) {
if(!$value) return '';
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>

<input type = "file"> EMPTY

i have this problem regarding file upload on php.
I always get this error msg.
Warning: file_get_contents(): Filename cannot be empty in
C:\xampp\htdocs\omf2\emprecords\add8.php on line 25
this is my line 25
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
But still saves the info on my database.
What i am trying to do is save the rest of the records on my database even if not selecting a file to upload. And yes the records are saved and the Attachment field (mediumblob) is [BLOB - 0 B]
Question: How can i eliminate the error/warning message? (because everything is really fine)
<meta http-equiv="refresh" content="2;URL='emphistory.php'">
<?php
{
echo "<center><font color='#AAA' size='3'><br/>Record Added!</center>";
}
?>
<?php
$con=mysqli_connect("localhost","root","","dbomf");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM valueholder");
$row = mysqli_fetch_array($result);
$count = '';
$IDNUM = $row['Val'];
$NS = addslashes($_POST ['NS']);
$ad = addslashes($_POST ['ad']);
$hr = addslashes($_POST ['HR']);
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES
('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
$db->close();
here
<form method="post" action="add8.php" enctype="multipart/form-data">
<td><strong>Attachment</strong></td>
<td>:</td>
<td><input type="file" name="uploaded_file"></td>
</tr>
</form>
<input type = "file">
should be
<input name="uploaded_file" type = "file">
also form method should be post and use enctype='multipart/form-data
<form action="" method="post" enctype="multipart/form-data">
<input name="uploaded_file" type = "file">
</form>
also check
$name = ''; $data = '';
if ((is_uploaded_file($_FILES['uploaded_file']['tmp_name']) && !($_FILES['uploaded_file']['error'])) {
$name = $con->real_escape_string($_FILES['uploaded_file']['name']);
$data = $con->real_escape_string(#file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
include ('../dbconn.php');
$query = "INSERT INTO tblemphist1 VALUES ('".$count."', '".$IDNUM."', '".$NS."', '".$ad."', '".$hr."', '".$data."', '".$name."')";
$result = $db->query($query) or die($db->error);
Use an if statement. For example:
if (!empty($_FILES)) {
$data = $con->real_escape_string(
file_get_contents($_FILES['uploaded_file'] ['tmp_name'])
);
}
Before accessing any property of $_FILES['uploaded_file'] you have to check the value $_FILES['uploaded_file']['error']. And yes, it's a good idea to check if such key exists at all - as with anything coming from the user, there is no guarantee that it exists in the request.
Simply check if the variable is not empty
$data = '';
if (!empty($_FILES['uploaded_file']['tmp_name'])) {
$data = $con->real_escape_string(file_get_contents($_FILES['uploaded_file']['tmp_name']));
}
if error doesn't affect your project just ignore it and add this code in top of your php.
<?php ERROR_REPORTING(E_ALL & ~E_NOTICE); ?>
it will ignore and hide the error. :)

php form not writing form data into mysql database

I have to code below - updated
php code
if(empty($_POST['formEmail']))
{
$errorMessage .= "<li>You forgot to enter your email</li>";
}
$varEmail = $_POST['formEmail'];
if(empty($errorMessage))
{
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
mysql_query($sql);
echo "Details added";
$_SESSION['status'] = 'success';
}
exit();
}
function PrepSQL($value)
{
// Stripslashes
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
form code
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<p>
<label for='formEmail'>Sign up to be notified when we go live!</label><br/>
<input type="text" name="formEmail" maxlength="50" value="<?=$varEmail;?>" />
</p>
<input type="submit" name="formSubmit" value="Submit" />
</form>
I'm not getting any errors and as far as I can tell the syntax looks fine but its not putting the email information into the database. Anyone have an idea of whats going on? As a side note I am a newb to all php.
You've forgotten to run the query! Put
mysql_query($sql);
straight after
$sql = "INSERT INTO emails(email) VALUES ('$varEmail')";
Make sure you run the $_POST variable through mysql_real_escape_string as well:
$varEmail = mysql_real_escape_string($_POST['formEmail']);
This will help protect you from SQL Injection attacks.
EDIT
One more tiny thing, I guess you want to set the session variable success when the form has submitted successfully. to do that you'll need to move
echo "Details added";
$_SESSION['status'] = 'success';
within the same if structure as the SQL query is run, otherwise it will never be set
Try:
$db = mysql_connect("servername","username","password");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("tableName" ,$db);
$sql = sprintf("INSERT INTO emails(email) VALUES ('%s')",mysql_real_escape_string($varEmail));
$results = mysql_query($sql);

Categories