I am a beginner at both mysql and php. And very badly stuck at this problem. Not sure where the problem is. but if i execute the insert query directly, it gets executed while if i accept it from user it dont(It is shown in the code). Probably the problem is with the $_POST[] method that i am using to retrieve the values submitted by user. I have submitted both the codes, addbooks.php(form from which user submits values) and add.php (to insert into the database).
//add.php
<?php
$con=mysqli_connect("localhost","root","","a_database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Using the following statements i am able to insert data.
//mysqli_query($con,"INSERT INTO books (book_name, book_author, book_price)
//VALUES ('Peter', 'Griffin',35)");
//But when i accept it from user(for which the following script is written), it is not working
if (isset($_POST['name']) && isset($_POST['author']) && isset($_POST['publication']) && isset($_POST['price']) && isset($_POST['stock']))
{
$book_name = $_POST['name']; //post method to retrieve the value submited by user
$book_author = $_POST['author']; //post method to retrieve the value submited
$book_publication = $_POST['publication']; //post method to retrieve the value submited by user
$book_price = $_POST['price']; //post method to retrieve the value submited by user
$book_stock = $_POST['stock']; //post method to retrieve the value submited by user
mysqli_query($con, "INSERT INTO 'books' (book_name, book_author, publication, book_price, book_stock) VALUES ($book_name, $book_author, $book_publication, $book_price, $book_stock)");
mysqli_close($con);
}
?>
//the form from which the values are being accepted(addbooks.php)is given bellow.
/*addbooks.php*/
<?php
//require 'connect.php';
//require 'newEmptyPHP.php';
//require 'filename.php';
?>
<html>
<body><form name="form1" method="post" action="add.php"> //call to addphp
<label>
Name of Book
<input type="text" name="name"/> //Accepting book details
<br>
Author
<input type="text" name="author"/> //Accepting book details
<br>
Publication
<input type="text" name="publication"/> //Accepting book details
<br>
Price
<input type="text" name="price"/> //Accepting book details
<br>
Stock
<input type="text" name="stock"/> //Accepting book details
<br>
submit //submitting th datails
<input type="submit" name="Submit" value="Submit"/>
</label>
</form>
</body>
</html>
You have to enclose the character values within quotes also no need of quotes for table name (Instead of quotes you can use backticks ` for tablename and column names in a query. And the values should be enclosed within quotes only).
mysqli_query($con, "INSERT INTO `books` (book_name, book_author, publication, book_price,
book_stock) VALUES ('$book_name', '$book_author', '$book_publication', $book_price,
$book_stock)");
Remove the single quotes from books and it should work.
Also the best way to debug this kind of problem is store the sql query in the string and using echo and print the query. And then look what query it is forming and first try to directly execute it on mysql shell
mysqli_query($con, "INSERT INTO books (book_name, book_author, publication, book_price, book_stock) VALUES ('{$book_name}', '{$book_author}', '{$book_publication}',$book_price, '{$book_stock}')");
Related
I have created a drop down list as well a input type for for category and name but in both the case as i click next it directs me to another page but nothing saves in my database.
company_account is the table name in which data has to be inserted it has four rows id, category, cname, about
<?php include( "./inc/header.inc.php");
require( "./inc/connect.inc.php"); ?>
<div>
<form action = "payment.php" method= "POST">
<select id="category" name="category" class="old_ui_selector">
<option value="0" selected="1">Choose your category</option>
<option value="">Accounting Firm</option>
<option value="">Agriculture</option>
<option value="">Automotive</option>
<option value="">Aerospace/Defence</option>
<option value="">Building Material</option>
</select>
</div>
<br>
<input type = "text" name="cname" placeholder= "Name"/>
<br><br>
By clicking Next you agree to the Terms and Conditions.
<br>
<input type = "submit" name="comp" value="Next"/>
</form>
<?php
if(isset($_POST['comp']))
{
$category=$_GET['category'];
$cname = $_POST['cname'];
$ins=mysql_query("insert into company_account (category) values ('$category')");
$insert = mysql_query("INSERT INTO company_account VALUES ('','$category','$cname','$about')");
if($ins)
if($insert)
{
echo "<br>".$category."inserted";
}
else
{
echo mysql_error();
}
}
?>
You have a few issues there, the first is you are using mysql, either update it to mysqli or better still PDO.
Second your form is submitting using POST and yet you try to collect the category using GET.
You also need to supply the contents of your connect.inc.php WITHOUT THE IP AND PASSWORD so people can have a look at the config.
I would suggest before going any further you have read here and get a better understanding before you proceed.
https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
Best of luck.
Note: mysql: This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
You have provided with the form action and that will redirect after clicking the submit button.
You have written the INSERT STATEMENT in the same page itself and that will not even work for you.
First Remove up the action="" and then you redirect it based on the data saved.
HTML:
<form action = "" method= "POST">
</form>
And you Option value is missing out values and after the form is submitted the values will not be entered into the DB. Hence you need to do the following.
Replace:
<option value="">Accounting Firm</option>
With:
<option value="Accounting Firm">Accounting Firm</option>
PHP Code for Insert:
You Insert Code will not work since you have not provided with the table values for insert operations.
Syntax:
INSERT INTO TABLENAME(`columnname1`,`columnname2`,.....) VALUES(VALUE1,VALUE1,....)
Hence you are advised to use the correct table structure for the Operations and then insert the data.
INSERT QUERY:
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
You can insert all in the single query itself and then redirect using the header location.
Use header Location for redirection to particular page after the data has been saved.
header('location : http://www.google.co.in');
PHP PART:
<?php
if(isset($_POST['comp']))
{
$category=$_POST['category'];
$cname = $_POST['cname'];
$insert = mysql_query("INSERT INTO company_account(`category`,`name`,`about`) VALUES ('$category','$cname','$about')");
$rows = mysql_affected_rows();
if($rows=0)
{
echo mysql_error();
}
else
{
ob_start(); // Refresh the Output Buffer
header('location: http://www.google.co.in');
exit;
}
}
?>
Note: $about you are using in the Insert Statement but no values are provided over to the Insert Statement. Please check to that.
I am trying to build an "admin" section of my website. One where I can update customer status on work orders (or tickets if you prefer the term). I have it where I can input an int in a text field and hit submit to DELETE, but I cannot get my addRow function to work. It is not causing an error, which makes me believe that I am not passing my variables correctly.
Here are the forms on admin.php:
<form name="newRow" METHOD="post" ACTION="q.php">
Status of New Entry: <input type="text" value="Open" name="newStatus" /><br>
Type of Maintenance being completed: <input type="text" value="Software Maintenance" name="maintType" /><br>
<input type="submit" value="Add" name="newEntry" />
</form>
<form name="delRow" METHOD="post" ACTION="q.php">
<input type="text" name="deleteID" />
<input type="submit" value="Delete" name="delEntry"/>
</form>
As for my q.php, here is what I have after I connect to my db (which again, I have no problems using the delEntry/delRow section, so I can't see how a connection/mysqli initialization problem would be the issue:
//prepare statements
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
$addData->bind_param("s,s", $newStatus, $maintType);
$delData = $conn->prepare("DELETE FROM $tname WHERE id=?");
$delData->bind_param("i", $deleteID);
//end prepared statements
//if New Entry Button is pressed
$newStatus = isset($_POST['newStatus'])
? $_POST['newStatus']
: '';
$maintType = isset($_POST['maintType'])
? $_POST['maintType']
: '';
$addData->execute();
if ( false===$addData ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
else{
printf("rows inserted: %d\n", $addData->affected_rows);
}
//if Del Entry Button is pressed
if ( isset( $_POST['delEntry'] ) ) {
$deleteID = $_POST['deleteID'];
$delData->execute();
}
$addData->close();
$delData->close();
$conn->close();
?>
my columns are matching according to phpMyAdmin:
$addData = $conn->prepare("INSERT INTO $tname (status, mainttype) VALUES (?, ?)");
status and mainttype (yes 2 t). my ID (primary) is an auto_incriment so I left it out because I don't want to cause any key duplicate errors by accident. It's auto_incriment has been tested and seems to be working fine.
Too make it more fun, I added an echo $newStatus; after my prepared statement execution, and it comes back with the correct value. I appear to be having a problem with the addition of the new row. Still no error being generated.
printf("rows inserted: %d\n", $addData->affected_rows);
returns with 0 rows affected as well.
Simple comma issue. On:
$addData->bind_param("ss", $newStatus, $maintType);
I had it listed as:
$addData->bind_param("s,s", $newStatus, $maintType);
I have some problems while trying to send data from form to mysql database using php.I know how to fix this when i set form action to anothen page (<form action="example.php>, but i want that all procces stay on one page.
WHen i run my php script and enter name in both of fields and go send, only url page changes, nothing else.Hope u can help me.Thanks
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo"Error connecting to database". mysqli_connect_error();
}
if (isset($_POST['input_send']))
{
$name=($_POST['input_name']);
$lastname=($_POST['input_lastname']);
$insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";
echo"record added";
}
?>
<form action="" action="post">
First name: <input type="text" name="input_name"/>
Last name: <input type="text" name="input_lastname"/>
<input type="submit" value="send" name="input_send"/>
</form>
Your error is that you typed
action="post"
instead of
method="post"
Without a method specified, PHP will fall back to GET.
Hence your isset($_POST) will return false and you are not seeing 'record added'
Another error, as pointed out by echo_ME is that you are not submitting the MySQL Query to the Database:
$insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";
With the function mysqli_query you can perform your query:
mysqli_query($insert);
As noted by others you should escape your variables to prevent SQL Injections
change this
$insert="INSERT INTO test_mysql (name, lastname) VALUES ('$name', $lastname)";
to
mysqli_query("INSERT INTO test_mysql (name, lastname) VALUES ('$name', '$lastname')");
and this
action="post"
to
method="post"
and escape your variables like that:
$name=mysqli_real_escape_string($_POST['input_name']);
$lastname=mysqli_real_escape_string($_POST['input_lastname']);
<form action="<?=echo $_SERVER['PHP_SELF']?>" method='post'>
You can take info about the page url from your server.
It basicly action to the same page, i mean itself.
I have a form that submits steps and ingredients for recipes that I am practicing with for another project. I have set the form up to submit the data in an array, but I can't get the PHP code correct to insert the data into the database. I have pasted the form layout here. The form comes up as part of another PHP page that is called when the user enters a recipe name to add to the database. I would like to have 10 separate step entries on this form if I can figure out how to insert them correctly into the database.
<form action="add_recipe2.php" method="post">
<fieldset>
<legend>Add a Recipe</legend>
<table>
<tr>
<td>Recipe Name:</td>
<td><input type="text" name="recipename" value="$recipename"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[0][step]" placeholder="1"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[0][ingredients]" placeholder="Ingredients"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[1][step]" placeholder="2"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[1][ingredients]" placeholder="Ingredients"></td>
</tr>
<tr>
<td>Step:</td>
<td><input type="text" name="recipe[2][step]" placeholder="3"></td>
<td>Ingredients:</td>
<td><input type="text" name="recipe[2][ingredients]" placeholder="Ingredients"></td>
</tr>
</table>
<button type="submit">Add a Recipe</button>
<button type="reset">Reset</button>
</fieldset>
</form>
This is the PHP that enters the data into the database. The problem is when I only add two records to the database the last record still inserts, but it inserts a blank line. I need a way to only add the data that is being passed from the form even if it is only one line. I have researched this a long time and this represents one of the answers that I found. However, it still does not stop inserting into the database when there is no more data from the form.
$recipename = $_REQUEST["recipename"];
$conn = mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("test");
foreach($_POST['recipe'] as $recipe) {
// Add to database
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$_POST['recipename']."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
} //end foreach
I just can't figure this out. I need help. I suspect that I have to have a way to tell how many records I am actually sending if it is not the number of form entries that exist.
You will need to test if values in the array component are filled in before querying them. Also, you MUST escape all the insert values against SQL injection with mysql_real_escape_string():
$recipename = mysql_real_escape_string($_POST['recipename']);
foreach($_POST['recipe'] as $recipe) {
// Only insert if step is non-empty.
if (!empty($recipe['step']) {
// Add to database
// Escape against SQL injection
$recipe['step'] = mysql_real_escape_string($recipe['step'];
$recipe['ingredients'] = mysql_real_escape_string($recipe['ingredients'];
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$recipename."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
}
}
The fact is, even if the user doesn't fill in the information in the form for recipe[3], the empty values are still being submitted.
You have to validate your data before insert into the database:
function isValidRecipe($recipe){
// returns true if ingredients and step are not empty
return !(empty($recipe['ingredients']) || empty($recipe['step']));
}
foreach($_POST['recipe'] as $recipe) {
if (isValidRecipe($recipe)){
// Add to database
$sql1 = "INSERT INTO `recipes` (recipe, step, ingredients) VALUES ('".$_POST['recipename']."', '".$recipe['step']."', '".$recipe['ingredients']."')";
mysql_query($sql1, $conn) or die(mysql_error());
}
}
Note that this is the minimum validation, you should probably check everything more thoroughly.
This code works. I can't figure out how to insert data into db If user pressed "SAVE" button for the first time or update data.
The php side
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "success" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
UPDATE
Thanks to #jmlsteeke i found the way
Place this piece of code in html part
<?php
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('555', 'new', '0')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', 'new', 'new')") or die($db->error);
?>
And added following code into form
<input type="hidden" name="id" value="<?=$new_id?>"/>
In serverside script used
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
Thank you #jmlsteeke
A common way would be to store the id as a hidden field when you are editing the page. This way when the user submits the page, if there is an id present, you issue the UPDATE commands, and if there isn't one present, you know it's a new page, and issue the INSERT commands.
If you need me to be more thorough let me know.
Edit: Being More Thorough
I'll make a simple, complete, example of what I mean.
Form.php pseudo code
//set default values for fields
//print form tag
if (isset($'id',$_GET)) {
//fetch data from database
//print hidden id field
//override default values for fields
}
//print rest of fields using default values (possibly overridden)
DoForm.php pseudo code
//Sanitize user input
if (isset('id',$_POST)) {
//UPDATE database with user input
} else {
//INSERT new rows into table with user input
}
Let's say you have a php file called Form.php which is responsible for displaying the form, and another php script called DoForm.php which is responsible for handling the form.
If a user visits Form.php with no ID specified (http://example.com/Form.php) then it will display the following form:
<form method="post" action="DoForm.php">
<input type="text" name="name" value="" />
<input type="text" name="title" value="" />
... other stuff ...
</form>
The user will add some information, click on the submit button and DoForm will get the following POST variables:
"name" => "NewPageName"
"title" => "My First Webpag" [intetional typo, see later]
... other stuff ...
DoForm will check to see if $_POST['id'] exists. Since it doesn't DoForm issues the INSERT commands to add a new page.
Later on, the user realises the made a typo, and goes to fix it. The user clicks on the "Edit Page" control for "NewPageName" which will be http://example.com/Form.php?id=1
Form.php see's that id is set, so the form it prints out is as follows:
<form method="post" action="DoForm.php">
<input type="hidden" name="id" value="1"
<input type="text" name="name" value="NewPageName" />
<input type="text" name="title" value="My First Webpag" />
... other stuff ...
</form>
The user fixes their type, changing Webpag to Webpage, and hits submit. DoForm gets the following Post variables
"id" => 1
"name" => "NewPageName"
"title" => "My First Webpage"
... other stuff ...
DoForm sees that id is set, and so uses UPDATE instead of INSERT.
Any more clear?
MySQL has an INSERT ... ON DUPLICATE KEY UPDATE feature that will let you try to insert a row, or fall back to an update if it discovers a duplicate key (i.e. the row already exists).