Cannot add values in Database using PHP - 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.

Related

Can anyone tell me why this row is being inserted twice into my database?

When I click my 'Create' button I want the record to be added to my category table, however for some reason it is being added twice - even though I just click the button once. Any ideas why that may be? I can't see where else the
if (isset($_POST['create'])) { could be called from. I only have 4 pages in my whole project.
<?php require('dbConnect.php');
//use the variables we created in volleyLogin.php
session_start();
$username = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
echo "user name is " . $username . "<br>";
echo "user id is " . $user_id . "<br>";
if (isset($_POST['create'])) {
$category = ($_POST['category']);
$name = ($_POST['name']);
$phonenumber = ($_POST['phonenumber']);
$address = ($_POST['address']);
$comment = ($_POST['comment']);
//check if the category being entered is already there
$check="SELECT COUNT(*) FROM category WHERE cat_name = '$_POST[category]'";
$get_value = mysqli_query($con,$check);
//check the number of values of the category being posted
$data = mysqli_fetch_array($get_value, MYSQLI_NUM);
//if the category name already exists in the category table
if($data[0] >= 1) {
echo "This Already Exists<br/>";
}
else if ($data[0] < 1)
{
//if it's not in there, then add the category in the category table.
$sql = "INSERT INTO category VALUES(NULL, '{$category}', '$user_id')";
$rs1=mysqli_query($con, $sql);
if ($con->query($sql) === TRUE) {
echo "Yes, it's been added correctly";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
}
$con->close();
}
?>
<!doctype html>
<html>
<body>
<h2>Create new Contact</h2>
<form method="post" action="" name="frmAdd">
<p><input type="text" name = "category" id = "category" placeholder = "category"></p>
<p><input type="text" name = "name" id = "name" placeholder = "name"></p>
<p><input type="text" name = "phonenumber" id = "phonenumber" placeholder = "phone number"></p>
<p><input type="text" name = "address" id = "address" placeholder = "address"></p>
<p><input type="text" name = "comment" id = "comment" placeholder = "comment"></p>
<p><input type="submit" name = "create" id = "create" value = "Create new Contact"></p>
Exit
</form>
</body>
</html>
You're running the $sql query twice, with two different methods:
$rs1=mysqli_query($con, $sql);
if ($con->query($sql) === TRUE) {
That's why you're getting duplicate entries.
You should either remove $rs1 as it's not being used, or verify it's value on the conditional instead of running the function again.

phpmyadmin not using DEFAULT value when input is left empty

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">

Form does not go to action page on submit

Edit 2: I traced the code through the php, and realized that it was a faulty header that was causing it to bounce back. I've fixed the header and now the form behaves as it should. Thanks everyone for your help.
EDIT: I noticed the form is quickly refreshing when I submit, so I think it is going to the action page (createlist.php) and immediately bouncing back, so there must be some issue there. Here is the code for createlist.php:
<?php
if (!isset($_SESSION)) {
session_start();
}
if (!defined(__DIR__)) {
define(__DIR__, dirname(__FILE__));
}
require_once(__DIR__.'/../config.php');
//Connect to server and select database.
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Cannot connect to server');
//mysql_select_db(DB_DATABASE) or die('Cannot select database');
$tbl_name = 'lists'; //Table name
//Retreive data from form
$listname = $_POST['listName'];
$admin_id = $_SESSION['SESS_MEMBER_ID'];
$listtype = 'list';
//Create listname session variable for catinit.php
$_SESSION['listname'] = $listname;
//Insert new row
$sql = "INSERT INTO $tbl_name(admin_id, listname, listtype) VALUES ('$admin_id', '$listname', '$listtype')";
$result = mysqli_query($link, $sql);
if ($result) {
header("location: catinit.php");
} else {
die("Could not create list");
}
//mysql_close();
?>
I have 2 forms on a page, and while it was working before, since adding the backend handling of the information it has broken. Now when I submit either of the forms on the page nothing happens, it does not even attempt to load the action pages. I am completely lost as to what is stopping it from submitting, as everything looks like its working.
<h1>Create a New List</h1>
<form action = "createlist.php" method = "POST" id = "formId" onsubmit = "formValidate(0, 0, 0, 1, 'formId', 'submitError', event)">
<p>List Name:
<input type = "text" id = "listName" name = "listName" placeholder = "New List" onblur = "listNameValidate('listName','errorName1')" required><span class = "error" id = "errorName1"></span></p>
</form>
<h2>Categories</h2>
<ul class = "catList" id = "list">
<table>
<?php
$cats = array('Produce', 'Meat/Dairy', 'Baked Goods', 'Dry/Canned Goods', 'Household Items');
//Check to see if Session version of array has different values
if (isset($_SESSION['catArray']) && $_SESSION['catArray'] != $cats) {
$cats = $_SESSION['catArray'];
} else {
$_SESSION['catArray'] = $cats;
}
foreach ($cats as $cat) {
$index = array_search($cat, $cats);
echo '<tr><td><li>'.$cat.'</li></td><td> Remove</td></tr>';
}
?>
</table>
</ul>
New Category: <br>
<form action = "addcat.php" method = "POST" id = "addcat">
<input type = "text" id = "newCategory" name = "newCat" placeholder = "Category name" onblur = "listNameValidate('newCategory','errorName2')">
<input type = "hidden" name = "catArray" value = "<?php echo htmlentities(serialize($cats)); ?>" >
<input type = "submit" value= "Add" class = "add"><span class = "error" id = "errorName2"></span>
</form>
<h2>Invite Members</h2>
Add a new Member: <br>
<input type = "email" id = "email" name = "Email" placeholder = "Email Address" onblur = "emailValidate('email', 'errorEmail')">
<input type = "button" value = "Add" class = "add" ><span class = "error" id = "errorEmail"></span>
<p><input type = "submit" form = "formId" value = "Create"></p>
<p class = "submitError" id = "submitError"></p>

no response when form is sent

I am trying to crewate a form fro listing databases on mysql, select one from the radio list and create a table with required parameters but it acts like it isn't even submitting. I see the url change but my code isn't running at all.
This is the form data:
SELECT DATABASE TO WORK WITH
<form action = "createtable.php" action = "post">
<?php
$query = "SHOW DATABASES";
$result = mysql_query($query, $connect);
if(!$result){echo mysql_error(); var_dump($result);
var_dump($connect); var_dump($query);}
while ($row = mysql_fetch_array($result))
{echo '<input type = "radio" name = "db"/>' . $row[0] . "<br>";}
?>
<input type = "text" name = "text" />
<input type = "submit" name = "submit" value = "submit" />
</form>
and the code to execute is:
<?php
if(isset($_POST['submit'])){
echo 'submit done';
$db = $_POST['db'];
$query = "USE $db";
$result = mysql_query($query, $connect);
if(!$result){echo 'no' . mysql_error();}
echo 'working';
$table = 'rio';
$id = 'id';
$idtype = 'int';
$idno = '11';
$staffmenu = 'staffmenu';
$stafftype = 'varchar';
$staffno = '255';
$null = 'NOT NULL';
$ai = 'auto_increment';
$key = 'id';
$query ="CREATE TABLE staff
($id $idtype($idno) $null $ai,
$staffmenu $stafftype($staffno) $null,
subj varchar(255) NOT NULL,
PRIMARY KEY ($key))";
var_dump($query);
$result2 = mysql_query($query, $connect);
if(!$result2){echo mysql_error();}
//session_destroy();
}
?>
i tried to use a different variable to trigger the code asides submit but that didn't work either. Any help will be appreciated. I am also aware of the deprecation of mysql, but i'm not totally sure how to migrate to mysqli so please bear with me.
To post your form you need method = "post" instead of action = "post"
<form action = "createtable.php" method = "post">
instead of
<form action = "createtable.php" action = "post">
Also, You need to add the value in your radio input as well,
echo '<input type = "radio" name = "db" value="'.$row[0].'" />' . $row[0] . "<br>";
Change your form's method type to post
you haven't mentioned your form's submission type

Can't insert the row into database

Why I can't insert into the database? What's wrong with my code?
<form action = "" method ="POST">
<center>
<b>Name</b><br><br>Quantity: <input type = "text" name = "name" style = "width: 155px"><br><br>
<b>Contact Number</b><br><br>Quantity: <input type = "text" name = "contact" style = "width: 155px" ><br><br>
<b>Address</b><br><br>Quantity: <input type = "text" name = "address" style = "width: 155px"><br><br>
<b>Spoon N1(₱25000.00)</b><br><br>Quantity: <input type = "text" name = "Squantity" style = "width: 155px" value = "0"><br><br>
<b>Tanabe Hypermedallion(₱15000.00)</b><br><br>Quantity: <input type = "text" name = "Tquantity" style = "width: 155px" value = "0"><br><br>
<b>Fujitsubo Legalis R(₱15000.00)</b><br><br>Quantity: <input type = "text" name = "Fquantity" style = "width: 155px" value = "0"><br><br>
<b>GCash Transaction No.</b><br>:
<input type = "text" name = "quantity" style = "width: 155px"><br><br>
<input type = "submit" value = "submit">
</center>
</form>
<?php
if(isset($_POST['submit']))
{
$name = empty($_POST['name']) ? die ("Input a name"): mysql_escape_string($_POST['name']);
$contact = empty($_POST['contact']) ? die ("Input a contact number"): mysql_escape_string($_POST['contact']);
$address = empty($_POST['address']) ? die ("Input a address"): mysql_escape_string($_POST['address']);
$spoon = empty($_POST['Squantity']) ? die ("Input a value"): mysql_escape_string($_POST['Squantity']);
$tanabe = empty($_POST['Tquantity']) ? die ("Input a value"): mysql_escape_string($_POST['Tquantity']);
$fujitsubo =empty($_POST['Fquantity']) ? die ("Input a value"): mysql_escape_string($_POST['Fquantity']);
$total = ($spoon * 25000) + ($tanabe * 15000) + ($fujitsubo * 15000);
$host = "localhost";
$user = "root";
$pass = "password";
$db = "eurocare";
$con = mysql_connect($host,$user,$pass,$db) or die ("Unable to connect");
$conn = mysql_select_db($db,$con);
$query = "INSERT INTO orders(name, contact, address, spoon, tanabe, fujitsubo) VALUES ('$name','$contact','$address','$spoon','$tanabe','$fujitsubo','$total')";
$result = mysql_query($query,$con) or die("Error in Query : $query ." .mysql_error());
exit;
mysql_close($con);
}
Using mysql_connect is deprecated, use mysqli instead.
I see you basically want to insert 7 elements, but declared only six...
INSERT INTO orders(name, contact, address, spoon, tanabe, fujitsubo) <-- ##!!SIX!!## VALUES ('$name','$contact','$address','$spoon','$tanabe','$fujitsubo','$total') <-- ##!!SEVEN!!##
Your submit button ie. HTML input element <input type="submit" ... ...> has to have the "name" attribute to be included in the $_POST array.
<input type = "submit" value = "submit" name="submit">
Without it if(isset($_POST['submit'])) would never resolve to true.

Categories