PHP + MySQL insert not working - php

I've been searching for some answers but can't figure out what's happening.
The SQL connection is working perfectly, I've checked it. So I have this POST method.
if(isset($_POST['new_data'])) {
$new_nm = mysqli_real_escape_string($db, $_REQUEST['new_name']);
$new_pstn = mysqli_real_escape_string($db, $_REQUEST['new_position']);
...
$db->query("INSERT INTO data (name, position, description, twitter, email, image) VALUES('$new_nm', '$new_pstn',
'$new_dscrpt', '$new_twt', '$new_mail', '$new_img')");
}
And here's the form from where I'm getting the data:
<form role="form" method="post">
<label>Name</label>
<input name="new_name" class="form-control" />
<label>Position</label>
<input name="new_position" class="form-control" />
...
<button type="submit" name="new_data">Submit!</button>
</form>
When I click in the button I don't get the data inserted. What am I doing wrong? I have another POST method with a different name which is working (that one makes an UPDATE).
Thanks a lot.

Well, I'll try to answer this question.
According to table structure, problem is in id field, which should be int with AUTO_INCREMENT.
Also, I want to make some suggestion for your input
if(isset($_POST['new_data']))
{
//Always check your input and sanitize it with htmlspecialchars() or htmlentities()
$new_nm = htmlspecialchars(isset($_REQUEST['new_name']) ? $_REQUEST['new_name'] : "");
$new_nm = mysqli_real_escape_string($db, $new_nm);
...
$db->query("INSERT INTO data (name, position, description, twitter, email, image) VALUES('$new_nm', '$new_pstn',
'$new_dscrpt', '$new_twt', '$new_mail', '$new_img')");
}

Related

How do I add a row to mysql db via php using controlled statements and html form for user input?

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

Unable to insert data into database(mysql) using php

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}')");

Error while trying to send data from form to MySql using PHP

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.

Value from form doesn't appear in database properly

I just want to transfer the information from a text form into a database, but the value doesn't appear in the database properly. Here's what I have:
HTML code, for the form:
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox">
<input type="submit" name="submit">
</form>
process.php
<?php
$con=mysqli_connect($host, $username, $password, $database);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$_POST [textbox]')");
// I also tried writing $_POST ['textbox'] instead; didn't make a difference.
?>
However, the output in the database is as follows:
User: test
Note: Array [textbox]
How would I be able to correct the value in the Note column (i-e to make it the value entered in the form)?
First off...you had a space between $_POST and ['textbox'];
it shoulda just been $_POST['textbox']...
But also you need to sanitize the data first so...
Try this
$input = mysqli_real_escape_string($_POST['textbox']);
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '$input')");
But really you should use PDO instead of the deprecated mysql_* functions...
Google PDO, and learn to do prepared statements.
Here it is with PDO...
$conn = new PDO("mysql:host=$host;dbname=$database",$username,$password);
$user = 'Test';
$note = $_POST['textbox'];
$sql = "INSERT INTO notes (User, Note) VALUES (:user,:note)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user,
':note'=>$note));
EDIT...
I also noticed your inputs aren't closed, there should be a / at the end of each...
<form method="post" action="process.php">
<input type="text" maxlength="150" name="textbox" />
<input type="submit" name="submit" />
</form>
You have a space between $_POST and [textbox]. $_POST is an array. Hence, Array [textbox], ie: ArraySPACE[textbox]
You should remove the space, then look into using prepared statements. You should not use user submitted data directly without sanitizing it first.
$sql = mysqli_query($con,"INSERT INTO notes (User, Note)
VALUES ('test', '{$_POST['textbox']}')");

Insert data / update if already exists

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).

Categories