phpmyadmin not using DEFAULT value when input is left empty - php

I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>

$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.

You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);

use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">

Related

Cannot add values in Database using PHP

I am currently doing a project in adding values using database but I seem to have a problem. I am sure that my query is correct since I tried adding it manually in mysql. Only some of the fields seem to be able to get what I input. I get the error
"Error: INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row) VALUES ('', '', '', 'White', '', '5', '', 'C', 'C')"
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "gracydb";
if (isset($_POST['addInventory']))
{
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
$sql = "INSERT INTO inventory (itemCode, dateReceived, typeOfFabric, details, unitOfMeasurement, amount, assignedOrderUse, section, row)
VALUES ('$itemcode', '$datereceived', '$fabric', '$details', '$measurement', '$amount', '$order', '$section', '$row')";
if (mysql_query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error($conn);
}
mysql_close($conn);
//header ('Location: .php');
}
?>
<form action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method = "POST">
Item Code: <input type = "text" name = "itemcode"><br>
Date Received: <input type = "date" name = "inventoryDateReceived"><br>
Type of Fabric: <input type = "text" name = "fabric"><br>
Unit of Measurement:
<select name = "measurement">
<option value = "Grams">Grams</option>
<option value = "Kilograms">Kilograms</option>
</select><br>
Amount: <input type = "number" name = "amount"><br>
Assigned Order/Use: <input type = "text" name = "order"><br>
Section: <input type = "text" name = "section"><br>
Row: <input type = "text" name = "row"><br>
<input type = "submit" value = "submit" name = "addInventory">
</form>
These indexes not matched with your input form names:
$_POST['itemCode']
$_POST['dateReceived']
$_POST['typeOfFabric']
These should be:
$_POST['itemcode']
$_POST['inventoryDateReceived']
$_POST['fabric']
Check your form inputs:
<input type = "text" name = "itemcode">
<input type = "date" name = "inventoryDateReceived">
<input type = "text" name = "fabric">
I don't see any sense in this part of the code:
if(isset($_POST['itemCode'])){ $itemcode = $_POST['itemCode']; }
if(isset($_POST['dateReceived'])){ $inventoryDateReceived = $_POST['dateReceived']; }
if(isset($_POST['typeOfFabric'])){ $fabric = $_POST['typeOfFabric']; }
if(isset($_POST['details'])){ $details = $_POST['details']; }
if(isset($_POST['unitOfMeasurement'])){ $measurement = $_POST['unitOfMeasurement']; }
if(isset($_POST['amount'])){ $amount = $_POST['amount']; }
if(isset($_POST['assignedOrderUse'])){ $order = $_POST['assignedOrderUse']; }
if(isset($_POST['section'])){ $section = $_POST['section']; }
if(isset($_POST['row'])){ $row = $_POST['row']; }
Your are just setting values (if isset) to new variables - but if they not exists you will still use undefined variables. Also there is no escaping to prevent sql-injections and validation of the given values!
I think you will get this error because of a missing variable.

Have 4 'ands' in a select statement

I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.

filling in form fields from previous database entry - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

PHP Multiple forms on same page with multiple buttons

I'm busy coding a website for a local business that does Milkshakes. Naturally, they wanted to show their flavours on the site and have a management page where they could edit them. I have gotten the flavours to show up on the main page, but I am having a problem with the management page.
I have a database set up that contains a list of the flavours. The 3 main things that I am trying to allow them to do is edit, delete and add new entries. Currently, I am calling out each row (or each flavour and its id) as separate forms with 2 submit buttons: one to save changes, and one to remove it.
Code is below:
for the management page:
<?php
$con = new PDO('mysql:host=host;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT * FROM FlavourShakes";
$data = $con->query($query);
$rows = $data->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$flavour = $row['Flavour'];
print "<form action=\"saveFlavorShakes.php\" method=\"post\"> \n
<fieldset> \n
<input name=\"id\" value=\"$id\" readonly/> \n
<input name=\"Flavour\" value=\"$flavour\" /> \n
<input type=\"submit\" name=\"edit\" value=\"Save\"> \n
<input type=\"submit\" name=\"edit\" value=\"Remove\"> \n
</fieldset> \n
</form> \n";
}
?>
<form action="saveFlavorShakes.php" method="post">
<fieldset>
<input name="Flavour" />
<input type="submit" name="edit" value="Add">
</fieldset>
</form>
and on my processing page:
<?php
$flavour = $_POST['Flavour'];
$id = $_POST['id'];
$btnType = $_POST['edit'];
$con = new PDO('mysql:host=hostname;dbname=dbname', "user", "password");
$con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "";
try
{
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
break;
}
//I know I haven't added a case for the remove button yet.
$statement = $con->prepare($query);
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
$count = $statement->execute();
header('Location: EditFlavorShakes.php');
}
catch(PDOException $e) {
if ($btnType = "save"){
$notice = "saveBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
} elseif($btnType = "delete"){
$notice = "delBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}elseif($btnType = "add"){
$notice = "addBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}else{
$notice = "otherBad";
$error = $e->getMessage();
$_POST['notice'] = $notice;
$_POST['error'] = $error;
}
echo $notice;
echo $e->getMessage();
//header('Location: EditFlavorShakes.php');
}
?>
Currently, I don't have any entries in the database. However, when I try to add Chocolate and click the Add button, I get this error:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
What I don't understand is why it $_POST['edit'] set to save instead of add? I feel like I am overlooking some stupidly simple mistake in my code. If anyone can help me I would appreciate it.
Thanks in advance.
You need to move the right $statement calls into each case -
switch($_POST['edit']){
case'Save':
$query = "UPDATE FlavorShakes
SET Flavour= :name,
WHERE id = :id;";
$notice = "saveOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this query needs multiple values bound
$statement->bindValue(":id", $id);
$statement->bindValue(":name", $flavour);
break;
case'Add':
$query = "INSERT INTO FlavourShakes(Flavour) VALUES (:name);";
$notice = "addOK";
$_POST['notice'] = $notice;
$statement = $con->prepare($query);
// this one needs one value bound
$statement->bindValue(":name", $flavour);
break;
}
//I know I haven't added a case for the remove button yet.
$count = $statement->execute();
You're also missing several tests (you're assigning) in your if statement. Replace = with == -
if ($btnType == "save"){
...
} elseif($btnType == "delete"){
...
}elseif($btnType == "add"){
...
}else{
...
}
This error message:
saveBadSQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
is because you try this line when there is no :id
$statement->bindValue(":id", $id);
And you always get saveBad cause you assign in your control:
if ($btnType = "save"){
Fix to:
if ($btnType === "save"){

Change a variable of a variable

I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.

Categories