HTML form, set blank form to NULL - php

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;
}

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

PHP form dumps entire MySQL database unless neither input variable exists in the database

I have a form that searches a MySQL database using PHP. Currently, when a user inputs a search into one of two fields, the entire contents of the database are displayed. Also, if the user leaves both fields blank, again, the entire contents of the database will be displayed.
However, if the user inputs random information into both of the fields, then the results page will be blank.
The assumed usage of this form is that the user can search for an article based on the article's title, the article's author or organization, or the article's title and its author or organization by either filling out one or both of the fields.
What I'm trying to figure out is:
Why the results page keeps displaying all of the database contents.
and
How to ensure that the database is actually being queried rather than just being dumped by a coding error.
Code follows below:
search.php:
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="articletitle" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="articleorganization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
searchdb.php
<?php
include('settings.php');
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
while ($row = mysql_fetch_array($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
When both are blank, your query states:
WHERE field LIKE '%%'
which matches everything.
The same happens when either one is blank, because you are using an OR to join the where clauses.
You can prevent this from happening, by checking the inputs aren't blank:
<?php
if (!((empty($_POST['field1']) || empty($_POST['field2']))) {
//run your query
}
Following on the post by #sberry.
if (isset($_POST['articletitle']) && $_POST['articletitle'] != "")
The variable can be set, but still be an empty string.
The method used by #xbonez is simpler as
if (!empty($_POST['articletitle'])) is the same as the above example that requires two tests
Have you tried xbonez method?
To be complete, this checks that at least one of the fields has been filled in:
if (!empty($_POST['articletitle']) || !empty($_POST['articleorganization'])) {
$query = "SELECT * from `articles` WHERE ";
$query .= "`articletitle` LIKE '%" . mysql_real_escape_string($_POST['articletitle']) . "%' ";
$query .= "OR `articleorganization` LIKE '%" . mysql_real_escape_string($_POST['articleorganization']) . "%'";
$sql = mysql_query($query);
} else {
// No results
}
Things that will only be used if one of the fields is filled in like:
$query = "SELECT * from `articles` WHERE ";
are placed inside the the if() statement, otherwise they are being parsed unneccesarily.
No need to create an array and then convert it into a string. ".=" will concatenate the string fragments into the final query string.
Matters of personal preference:
MySql keywords written in full caps, I find it makes the statements easier to read.
There are numerous discussions about it.
Search for "sql uppercase keywords style"
Using backticks around table and fieldnames:
Allows the use of reserved keywords for table or fieldnames (count, case, default, div, index, key, limit, option, order, etc...).
Reduces work for the mysql parser, it doesn't need to check whether there is a reserved word conflict.
Avoids problems if your table or field name becomes a reserved keyword in the future.
Again, numerous discussions. Search for "mysql backtick"
MySQLdocumentation:
9.3. Reserved Words
9.2. Schema Object Names
Look for "quoted identifier" on this page.
Also, if you might be migrating to a different database app in the future , you could use double quotes instead of backticks, look for "ANSI_QUOTES".
9.2.4. Function Name Parsing and Resolution
Look for "quoted identifier" on this page.
Tested this, and it should do exactly what you want.
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
EDIT
It appears your form is passing empty values, so instead of checking isset, check !empty. I have updated the code above.

PHP code for quotation marks and ifelse statement - correct syntax?

This is a PHP page which displays the results from a query using JOIN
(based on one from a tutorial and adapted for my database):
<?php
$connection = mysql_connect("localhost", "root", "PASSWORD") or die("Error connecting to database");
mysql_select_db("products", $connection);
$result = mysql_query("SELECT * FROM buyers LEFT JOIN products USING (id);", $connection) or die("error querying database");
$i = 0;
while($result_ar = mysql_fetch_assoc($result)){
?>
<table>
<tr <?php if($i%2 == 1){ echo "class='body2'"; }else{echo "class='body1'";}?>>
<td>
<?php echo $result_ar['buyer_name']; ?></td>
<td>
<?php echo $result_ar['manufacturer']; ?>
</td>
<td>
<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?>
</td>
</tr>
</table>
<?php
$i+=1;
}
?>
However, it's not the join that's the issue, here, but this PHP coding:
<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?>
I tried this and it displayed the following (full result of code at beginning of this question):
John Zanussi "1500 Washing Machine"
James Hotpoint "3000 Washing Machine"
Simon Hotpoint
I was surprised it worked, it was just a test statement to see if the code worked.
http://www.w3schools.com/php/php_if_else.asp was my tool for this.
If I'm correct, it means it will put any array from the product_name column in quotation marks but if the column is blank then it will not display quotation marks.
Just checking to see if I'm correct - trying to brush up on my PHP skills here!
You're correct. The ternary operation in your code is equivalent to:
// If the product_name isn't empty, surround it in quotes.
if (!empty($result_ar['product_name']))
{
$result_ar['product_name'] = "\"{$result_ar['product_name']}\"";
}
Using the ternary operation here is kind of confusing since the first case (empty value) still results in an empty value. More often you would see the opposite -- ternary operation used to create a default value for an empty variable.
In your context of echoing out the variable, you can shorten it to this expression. There's no need to reassign the variable before echoing it. You can echo the result of the ternary operation.
// Based on your version...
echo ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"';
// Clearer version with the empty case last rather than first...
echo !empty($result_ar['product_name']) ? "\"{$result_ar['product_name']}\"" : "";
To use a ternary operation to assign a class (which could have bold text, for example) you could use something like this inside a table cell:
<td class='<?php echo $result_ar['product_name'] == "Zanussi" ? "special_bold_class" : "regular_class";?>'>
The result is:
<td class='special_bold_class'>

PHP SQlite Database Form

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.

Inserting specific values into a DB, and displaying it on a table?

I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.

Categories