Can't insert the row into database - php

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.

Related

Get the value from previous page php, sql

I can't get the value of id from update.php and give to it another page which is update2.php
Here is the code of my update.php
<form method = "post" action = "update2.php ?id=".$row['0'].">
<p class = "head">Update Account Basic Info</p>
<p class = "form">
<input type = "text" class = "name" name = "f_name" placeholder = "First Name">
<input type = "text" class = "name" name = "l_name" placeholder = "Last Name">
<br>
<input type = "text" class = "other" name = "email" placeholder = "Email Address">
<br>
<input type = "numeric" class = "other" name = "mob_no" placeholder = "Mobile Number">
<br></br>
<input type = "submit" name = "save" value = "Update Account">
</p>
</form>
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<p class = 'sub'>Current Account Basic Info</p>";
echo "<p class = 'form'>ID Number: ".$row['0']."<br>";
echo "First Name: ".$row['1']."<br>";
echo "Last Name: ".$row['2']."<br>";
echo "Email: ".$row['3']."<br>";
echo "Mobile Number: ".$row['4']."</p>";
}
mysql_close();
?>
Here is my code of update2.php
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
echo $_GET['id'];
mysql_query("UPDATE tblaccount SET f_name = '$_POST[f_name]', l_name = '$_POST[l_name]', email = '$_POST[email]', mob_no = '$_POST[mob_no]' WHERE id_no = '$_GET[id]'");
echo "<h1>Account Updated</h1>";
mysql_close($con);
?>
My problem is my $_GET[id] function in update2.php can't get the value of id_no in update.php
You wont get the right result when you use
action = "update2.php ?id=".$row['0']."
because, .$row['0']. is not php.. It is just HTML..
Instead, you will have to use
action = "update2.php?id=<?php echo $row['0']; ?>"
UPDATE
Since you are getting Undefined variable: row error, it means that $row is null.
Thus, Move
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
to the line before opening the <form>.
ie, Now, the code should be like
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db("dbfacebook", $con);
$query = "SELECT id_no, f_name, l_name, email, mob_no FROM tblaccount WHERE id_no = '$_GET[id]'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
<form method = "post" action = "update2.php?id=<?php echo $row['0']; ?>">
}
?>

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>

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.

how to add data in 2 table in only one form

HTML CODE
<form method = "POST" action = "register.php">
<div class = "register">
<center>
<div class = "heading"></br>
<strong>--- REGISTER ---</strong></br></br>
</div>
</center>
<div class = "registration">
First Name: <input type = "text" placeholder = "Enter First Name" name = "Cus_fname" style = "margin-left: 48px;" required></br></br>
Last Name: <input type = "text" placeholder = "Enter Last Name" name = "Cus_lname" style = "margin-left: 49px;" required></br></br>
Username: <input type = "text" placeholder = "Enter Username" name = "Cus_Uname" style = "margin-left: 55px;" required></br></br>
Password: <input type = "password" placeholder = "Enter Password" name = "Cus_Pword" style = "margin-left: 61px;" required></br></br>
Address: <input type = "text" placeholder = "Enter Address" name = "Cus_address" style = "margin-left: 67px;" required></br></br>
Contact No.: <input type = "text" placeholder = "Enter Contact Number" name = "Cus_contactnum" style = "margin-left: 38px;" required></br></br>
Email: <input type = "text" placeholder = "Enter E-mail Address" name = "Cus_email" style = "margin-left: 88px;" required></br></br>
<input type = "submit" name = "submit" value = "Submit" style = "margin-left: 110px;"></br>
</div></br>
</form>
PHP CODE
<?php
if(isset($_POST['submit'])){
$cf = $_POST['Cus_fname'];
$cl = $_POST['Cus_lname'];
$cu = $_POST['Cus_Uname'];
$cp = $_POST['Cus_Pword'];
$ca = $_POST['Cus_address'];
$cn = $_POST['Cus_contactnum'];
$ce = $_POST['Cus_email'];
include("config.php");
mysqli_query($con, "INSERT INTO account (Cus_ID, Cus_Uname, Cus_Pword) VALUES ('null', '$cu', '$cp')");
mysqli_query($con, "INSERT INTO client (Cus_ID, Cus_lname, Cus_fname, Cus_address, Cus_contactnum, Cus_email) VALUES(null, '$cl', '$cf', '$ca', '$cn', '$ce')");
mysqli_close($con);
}
?>
The problem is that it's only adding on one table which is my client table and it only add 1 data to my account table no more than that
Im Using MySQL Workbench for my database
Using a prepared statement allows you to protect from SQL Injection. Checking all your posts helps ensure that they have some value if needed.
<?php
if(isset($_POST['submit'])){
// Populate each variable
$cf = isset($_POST['Cus_fname'])?$_POST['Cus_fname']:"";
$cl = isset($_POST['Cus_lname'])?$_POST['Cus_lname']:"";
$cu = isset($_POST['Cus_Uname'])?$_POST['Cus_Uname']:"";
$cp = isset($_POST['Cus_Pword'])?$_POST['Cus_Pword']:"";
$ca = isset($_POST['Cus_address'])?$_POST['Cus_address']:"";
$cn = isset($_POST['Cus_contactnum'])?$_POST['Cus_contactnum']:"";
$ce = isset($_POST['Cus_email'])?$_POST['Cus_email']:"";
include("config.php");
if ($stmt = $mysqli->prepare("INSERT INTO account (Cus_Uname, Cus_Pword) VALUES (?, ?, ?)")) {
// bind parameters for markers
$stmt->bind_param("sss", $cu, $cp);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
if ($stmt = $mysqli->prepare("INSERT INTO client (Cus_lname, Cus_fname, Cus_address, Cus_contactnum, Cus_email) VALUES (?, ?, ?, ?, ?)")) {
// bind parameters for markers
$stmt->bind_param("sssss", $cl, $cf, $ca, $cn, $ce);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
mysqli_close($con);
}
?>
This code assumes that your ID Column uses Auto-Increment. In this case, you do not need to include the IS in INSERT, it will be done automatically when the query runs.
Check the query for your account table.
mysqli_query($con, "INSERT INTO account (Cus_ID, Cus_Uname, Cus_Pword)
VALUES ('null', '$cu', '$cp')");
You have placed a typo 'null' which is a string into your Cus_ID which i assume the datatype is INT since it is a ID. Remove the single quotes null and see if that works.

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

Categories