PHP SQlite Database Form - php

I have been struggling through PHP and sqlite for a bit now and I'm just confusing myself.
I have an html form that accessess a php script called processFeedback.php.My html code looks like this..
<html>
<head>
</head>
<body>
<form action="processFeedback.php" method="POST">
<table>
<tr>
<td>Name:</td><td><input name="name"/></td>
</tr>
<tr>
<td>Email:</td><td><input name="email"/></td>
</tr>
<tr>
<td>Comments:</td><td><textarea name="comments"></textarea></td>
</tr>
<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>
and my php file looks like this...
<?php
try
{
//open the database
$db = new PDO('sqlite:feedback.db');
$name = $_POST["name"];
$email = $_POST["email"];
$comments = $_POST["comments"];
//Insert record
$db->exec("INSERT INTO feedback (name, email,comments) VALUES ('&name', '&email','&comments');");
//now output the data to a simple html table...
print "<table border=1>";
print "<tr><td>Id</td><td>Name</td><td>Email</td><td>Comments</td></tr>";
$result = $db->query('SELECT * FROM feedback');
foreach($result as $row)
{
print "<tr><td>".$row['feedbackid']."</td>";
print "<td>".$row['name']."</td>";
print "<td>".$row['email']."</td>";
print "<td>".$row['comments']."</td>";
}
print "</table>";
$db = NULL;
}
catch(PDOException $e)
{
print 'Exception : ' .$e->getMessage();
}
?>
And here is my table creation method...
CREATE TABLE feedback (feedbackid INTEGER PRIMARY KEY,name TEXT,email TEXT,comments TEXT);
The form is outputting the table headers and also a record that I manually entered using the Terminal but it won't insert a record in??? Can anyone see an easy mistake?
Disco

//Insert record
$db->exec("INSERT INTO feedback (name, email,comments)
VALUES ('&name', '&email','&comments');");
One obvious issue is that you're doing no error checking:
if (1!=$db->exec("INSERT...)) {
print "Error: " . implode('/',$db->errorInfo()) . "\n";
}
While I'm not overly familiar with PDO, I don't see how your placeholders are getting mapped to the corresponding PHP variables - which is probably the cause of the error:
$bound=array(
$_POST["name"], $_POST["email"], $_POST["comments"]
);
$stm=$db->prepare("INSERT INTO feedback (name, email,comments)
VALUES (?, ?,?));"
if (!$stm || !$stm->execute($bound)) {
print "Error: " . implode('/',$db->errorInfo()) . "<br />\n";
}

Check to make sure the PK column [feedbackid] is auto-generated in the database (AUTOINCREMENT).
EDIT: THis is not absolutely necessary but the lack of an explicit AUTOINCREMENT may be confusing the middleware. At least it cannot hurt to try adding an explicit AUTOINCREMENT to another table to test.

I had a similar problem in a PHP form where I used php to get data from a sqlite database and autofil fields.
You have
$db->exec("INSERT INTO feedback (name, email,comments) VALUES
('&name', '&email','&comments');");
I beleive that this should be
$db->exec("INSERT INTO feedback (name, email,comments) VALUES (" .
$name . "," . $email . "," . $comments . ");");
The period "." character combinds strings. Because you need exec() to basically be a one line sting (sql statement), you want to combine your written text with your variables as a string. I am not sure what the & does in place of the $ in a variable name in php, but I know in some functions the variable prefix is actually : instead of $ but the : variables have to be "bound" from a value.
see what does 'period' character do in php
I am by no means an expret but I happen to have the same problem as you so I hope I helped :)
EDIT: I just noticed this article is quite old. I hope this helps someone in the future with newer PHP.

Related

How to export table in html to database using php?

I am trying to export a full table into SQL using data from an HTML table. I know how to export one row, but can't understand how to export multiple rows. Any advice?
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<form action="insertorder.php" method="post">
<td name="Item_ID[]"><?=$row["item_id"]?></td>
<td name="name[]"><?=$row["ITEM_NAME"]?></td>
<td name="suggested_qty"><?=$row["suggested_qty"]?></td>
<td name="price" class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result[]' class="resultinput" /></td>
</tr>
<?php endwhile?>
<input type="submit" class="btn btn-dark" value="Submit">
</table>
</form>
Export script:
$sql = "INSERT INTO ms_order VALUES (item_id, item_name, order_quantity, total)";
for ($i=0; $i<count($_POST['Item_ID']); $i++) {
$sql .= '(\'' . $_POST['Item_ID'][$i] . '\', \'' . $_POST['name'][$i] . '\', \'' . $_POST['editedvalues'][$i] . '\', \'' . $_POST['result'][$i] . '\')';
if ($i<count($_POST['Item_ID']) - 1) {
$sql .= ',';
}
echo $sql;
}
The problem on your code it's that you're creating a new form for each fetched row on the while loop. By doing this, you're sending only one row whenever the form is submitted. To solve this you should place the form tag outside the while loop. Also, let me share with you a cleaner way to accomplish what you're doing:
$sql = "INSERT INTO ms_order (item_id, item_name, order_quantity, total) VALUES ";
$sql .= implode(',', array_map(function($item_id, $name, $editedvalues, $result) {
return <<<SQL
({$item_id}, {$name}, {$editedvalues}, {$result})
SQL;
}, $_POST['Item_ID'], $_POST['name'], $_POST['editedvalues'], $_POST['result']));
This is what it does:
array_map function fetchs each index of a given array, you can pass as an argument as many arrays as you wish, it will iterate over each index so you will be able to use each value to manipulate it and return it.
Each iteration of the array_map will create a new array, so in the end what you get is an array of arrays containing the returned results. Finally, as you want to make a multiple INSERT, you concatenate each array with a colon using the implode function.
Note that you should sanitize the $_POST values as you might be vulnerable to SQL Injection and other security issues. For further information about it, check it out here.
Greetings,
Matt

How to add multiple selection checkboxes to mysql db?

I want the user be able to check multiple checkboxes, after which his/hers selection is printed on the html page and add each selection to my Mysql db. Unfortunately I only see the literal string 'Array' being added to my db instead of the selected names.
My script looks as follows :
<html>
<head>
<title>checkbox help</title>
</head>
<?php
if (isset($_POST['submit'])) {
$bewoner_naam = $_POST["bewoner_naam"];
$how_many = count($bewoner_naam);
echo 'Names chosen: '.$how_many.'<br><br>';
if ($how_many>0) {
echo 'You chose the following names:<br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $bewoner_naam[$i] . '<br>';
}
echo "<br><br>";
}
$bewoner_naam = $_POST['bewoner_naam'];
echo $bewoner_naam[0]; // Output will be the value of the first selected checkbox
echo $bewoner_naam[1]; // Output will be the value of the second selected checkbox
print_r($bewoner_naam); //Output will be an array of values of the selected checkboxes
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('$_POST[bewoner_naam]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<body bgcolor="#ffffff">
<form method="post">
Choose a name:<br><br>
<input type="checkbox" name="bewoner_naam[]" value="kurt">kurt <br>
<input type="checkbox" name="bewoner_naam[]" value="ian">ian <br>
<input type="checkbox" name="bewoner_naam[]" value="robert">robert <br>
<input type="checkbox" name="bewoner_naam[]" value="bruce">bruce<br>
<input type="submit" name = "submit">
</form>
</body>
<html>
Thank you so much with helping me!!!
Kindest regards,
Martin
You can't insert an array into a singular column, it will show up as "array" as you're observing, so you've got two choices:
Insert multiple rows, one for each item, by looping over that array.
Combine them together using implode into a singular value.
The way your database is structured in your example it's not clear which of these two would be best.
Since $_POST['bewoner_naam'] is an array, you have to add each item in that array to the database. You can for example use a for loop for this:
$con = mysql_connect("localhost","usr","root");
mysql_select_db("db", $con);
foreach($_POST['bewoner_naam'] as $naam) {
$sql="INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES ('". mysql_real_escape_string($naam) ."')";
}
Note that I've used the mysql_real_escape_string function. You will ALWAYS want to include this. For the why and how, see: Sanitizing PHP/SQL $_POST, $_GET, etc...?
First thing is to avoid all mysql_* functions in PHP. They are deprecated, and removed in newer versions, and to top it all of, insecure. I advise you switch to PDO and use prepared statements.
This will not solve your issue however. The issue you are having is that in the code where you combine the SQL you are concatenating the array with the string, that's why you only insert "Array". If you wish to insert all array items as a string, then you need to implode the array:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES (:checkboxes)";
$statement = $pdo->prepare($sql);
$statement->bindValue(":checkboxes", implode(",", $_POST["bewoner_naam"]);
$statement->execute();
Although, storing multiple values as a comma separated list in a database is not such a good idea, since it can become too un-maintainable through time, and produces more difficulty when obtaining such data, because you need to "re-parse" it after retrieving it from data.
As #Rodin suggested, you will probably want to insert each array item as a separate row, so I propose the following:
$sql = "INSERT INTO bewoner_contactgegevens (bewoner_naam) VALUES "
. rtrim(str_repeat('(?),', count($_POST["bewoner_naam"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach ($_POST["bewoner_naam"] as $bewoner_naam) {
$statement->bindValue($count++, $bewoner_naam);
}
$statement->execute();
This way you will create a bulk insert statement, with as many placeholders as there are selected checkboxes, and put each of their values on a separate line in the database.
For more on PDO, and parameter binding please refer to http://www.php.net/pdo

I'm using PHP and need to Insert into sql using a while loop

I'm after a little help. I have a page for a user to input upto 10 different rows of information. Dispatch details. I have created a page with my form using a loop..
<?php
session_start();
require("config.php");
require("header.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
<br><br><br></br>
<form action="insertdispatch.php" method="post">
<body>
<center>
<table>
<tr>
<td><center><b>Ref</td>
<td><b><center>Date</td>
<td><b><center>Service</td>
<td><b> <center>Tracking</td>
</tr>
<?php
$index = 1;
$name = 1;
while($index <= 10){
?>
<td><input type="text"
name="transno<?php echo $index;?>"
id="transno<?php echo $index;?>" />
</td>
<td><input type="text" name="date<?php echo $index;?>"
id="date<?php echo $index;?> "/>
</td>
<td><select name = "service<?php echo $index;?>"><?php
$viewsql = "SELECT * FROM dispatch_service ORDER BY service ASC";
$viewresult = mysql_query($viewsql);
while($row = mysql_fetch_assoc($viewresult)){
?> <option value=<?php echo $row['service'] ;?>>
<?php echo $row['service'] ;?></option>
<?php
}
echo "</select>";?>
<td><input type="text"
name="tracking<?php echo $index;?>"
id="tracking<?php echo $index;?>"/>
</td>
</tr>
<?php $index ++;
}?>
<center>
<td><input type="submit" value="Add Product" />
</form>
</center>
</td>
</tr>
</table>
</center>
<center><a href='javascript:history.back(1);'>Back</a>
</body>
</html>`
I have 10 of each text box, the name of the text box adds the value of index to the end. (with my limited coding experience I am very pleased with myself) so I go to the insertdispatch.php page and the plan is to insert each of these values into my table... now...I have no clue... and I cannot seem to figure out how I am going to do this...
I think I will need to use a loop again.. but I can't seem to figure out how I am going to call each of the $_POST values. I don't really want to use 10 different insert statements, as the form may increase in size. here is what I have so far..
<?php
session_start();
require("config.php");
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("hbt",$db)or do_error("Could not connect to the database");
$index = 1;
while($index <= 10){
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking) values ()";
mysql_query($insertsql);
$index ++;
}
//header("Location: " . $config_basedir . "home.php");
?>
I am not looking for anyone to finish the coding for me, but any tips would be grateful! :)
you can build 1 insert statement that inserts multiple rows:
INSERT into dispatch (trans_no, date, service, tracking) values
(1, '2013-09-12', 'myService1', 'on'),
(1, '2013-09-12', 'myService2', 'on'),
(1, '2013-09-12', 'myService3', 'on'),
(1, '2013-09-12', 'myService4', 'on'),
(1, '2013-09-12', 'myService5', 'on');
Just build this inside your the while, and execute it after the while has finished.
To build this query, you will need to perform the exact same loop as when you are generating the HTML, but now just fetch the values from $_POST instead of create a html field for them...
note while building your HTML, you are firing a static query inside your for loop. since this query is static, the results will also not change, and it is best to execute that query outside of the outer while loop.
(you really should read up more on basic HTML - tehre are lots of mistakes there even before considering the PHP code).
name="transno<?php echo $index;?>"
This is really messy too - you are creating extra work and complication for yourself. Use arrays:
name="transno[]"
If you do exlpicitly want to reference the item again then set the index:
id="transno[<?php echo $index; ?>]"
And at the receiving end....use a single insert statement to add the rows - not 10 seperate ones (it will be much faster).
You've already set up your while loop with $index - you could simply use that to iterate through the POST values, since you set their name attribute with an index. Consider:
$index = 1;
while($index <= 10){
$trans_no = $_POST["transno$index"];
$service = $_POST["service$index"];
$date = $_POST["date$index"];
$tracking = $_POST["tracking$index"];
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking)
VALUES($trans_no, $date, $service, $tracking)";
mysql_query($insertsql);
$index++;}
Though it would be much cleaner to set up your form inputs as arrays, as noted by others here.
Also, please read up on SQL injection. You need to sanitize any user input before it's inserted into a database - otherwise a malign user could wipe your whole database.

Trying to use query variable and form data to change tables in database

So as said in title I'm trying to use the query variable given from the page which directs to this one and the form data from THIS page to manipulate the database. I can't seem to get it right and I have no idea what I'm doing wrong. The code snippet looks like this:
<?php
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php' method='post'>";
Echo 'Username:<br>';
Echo '<input type="text" name="usernamecheck" size="14"><br>';
Echo 'Password:<br>';
Echo '<input type="password" name="passwordcheck" size="14"><br>';
Echo '<input type="submit" value="Send">';
Echo '</form>';
if (isset($_POST['usernamecheck'])) {
$sql2 = "SELECT * FROM `storedata`.`users` WHERE `username` LIKE '$_POST[usernamecheck]'";
$found_user_id = mysql_query($sql2, $conn);
print $found_user_id;
}
if (isset($_POST['usernamecheck'])) {
$sql3 = "INSERT INTO `storedata`.`basket` (user_id, ware_id, number, complete)
VALUES
('$found_user_id', '$ware_number', 1, 0)";
$derp = mysql_query($sql3, $conn);
print $derp;
}
?>
The document itself is usernamecheck.php, and I was just printing to try and locate the error. When i check the basket table nothing has happened, even though no error is displayed. Right now the variable $ware_number is causing errors. What am I doing wrong?
I have also made user_id and ware_id foreign keys in the storedata.basket table, since they are primary keys in their own respective table. This means they can only be specific values, but I'm testing with these values, primarily 1's and 0's...
What if $_GET['id'] is not set? it will fail. Also please read up into correct usage of SQL in PHP. Your code is vulnerable to SQL injection attacks and whatnot.
EDIT:
updated piece of code
if(isset$_GET['id'] && is_numeric($_GET['id']))
{
$ware_number = $_GET['id'];
Echo "<form action='usernamecheck.php?id=" . $_GET['id'] . "' method='post'>";
.....

HTML form, set blank form to NULL

I have a HTML form; I want to be able to set it so that if a field is empty, the field in the DB will actually be NULL and not just have the word NULL in the field. I thought that using this code would help, but it just puts the word NULL in the field.
PHP Code:
<pre>
<?php
if (isset($_POST['oc_item'])) {
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? $_POST['oc_itemdesc'] : NULL;
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES(''$oc_item','$oc_itemdesc')";
mysql_query($SQL);
if (mysql_query($sql)) {
echo '<strong><em>Your data has been submitted</em></strong><br /><br />';
} else {
echo '<p>Error adding submitted info: ' . mysql_error(). '</p>';
}
}
?></pre>
HTML Code:
<pre>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table>
<tr>
<td>Item Name</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_item" /></td>
</tr>
<tr>
<td>Item Description</td>
<td><input class="forms" type="text" size="50" maxlength="50" name="oc_itemdesc" /></td>
</tr>
</table>
<p><input type="submit" value="Submit item" /></p>
</form></pre>
I want the field to actually be NULL and not have the field contain the word NULL. Thanks in advance.
If you want to write NULL to a MySQL database, you really have to put NULL there without quotation marks.
Like this:
INSERT INTO table (column, column2) VALUES ('mystring', NULL);
It’s always a bit effort if you want to do this manually by hand, because you would have to make if-conditions for the query.
Remember: PHP null != MySQL NULL. They both do not know each other at all.
But I am still wondering, what does that all have to do with the question name? (SELECT unless)
You could write your code like this:
$oc_item = mysql_escape_string($_POST['oc_item']);
$oc_itemdesc = (isset($_POST['oc_itemdesc']) && trim($_POST['oc_itemdesc']) != '') ? "'" . mysql_escape_string($_POST['oc_itemdesc']) . "'" : 'NULL';
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('" . $oc_item . "', " . $oc_itemdesc . ")";
# sorry for adding " . all the time, but I dislike variables within strings :D
But I have to admit I do not like that much either, as it moves the duty to wrap quotation marks around MySQL strings away from the SQL-query itself.
If you printed out $sql, you'd see that it's inserting , 'NULL'.
You need to modify your code so that it inserts the work "NULL" (without '' quotes) or, better, doesn't insert that parameter at all (eliminate the entire , 'NULL' part of the string.
Try this:
$oc_itemdesc = (!empty($_POST['oc_itemdesc'])) ? "'".$_POST['oc_itemdesc']."'" : "NULL";
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item',$oc_itemdesc)";
As it stands you are adding 'NULL' instead of NULL so it is adding the words instead of the value.
Side Note: I would be careful and properly escape/encode the $_POST['oc_itemdesc'] as someone who put an apostrophe in the description would completely throw off the insert statement. For example: I don't like this would look like this:
$sql = "INSERT INTO catalog_dev (oc_item,oc_itemdesc)
VALUES('$oc_item','I don't like this')";//MYSQL Error
PPS: As it stands you are inserting TWICE:
mysql_query($SQL);//insert 1
if (mysql_query($sql)) {//insert 2
The function that I use for the MySQL data from the HTML forms.
function emptyHtmlFormToNull($arr){
foreach($arr as $key => $val){
if(empty($val) || strtolower($val) === 'null'){
$arr[$key] = null;
}
}
return $arr;
}

Categories