Insert row into MQSQL Database only under certain conditions - php

Before reading, please note that I am very new to both PHP and MYSQL. I have created a table in my MYSQL database. I would now like to 'spit out' this table onto a page through PHP. This part I seem to be okay with. After outputting the tables data into an HTML table, I would like to output an HTML form onto my page. So, I now have a table followed by a form. This form will contain a few text boxes that, when submitted, will post the data used to insert a new row into the preexisting table noted above.
All of the above code is currently in a PHP file named 'display.php'.
My Issue:
If the form described above is posting back to my 'display.php' file, after inserting a new row and displaying the new table information, what is stopping my code from inserting another new row full of NULL data? I'm sure I did a less than decent job of explaining this scenario so I will post some code.
HTML / PHP
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="insertdata.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
<?php
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
// Insert posted data into table
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
('$_POST[username]','$_POST[hardwareid]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
?>
</body>
</html>
Again, I am a complete beginner - and I understand this. I want to know, must the different parts of the above code be placed into multiple files? I don't want to have to go to a new address, which is why this is causing me so much confusion I'd say.

try some thing like this,
connection.php file
// Connect to MYSQL
$con = mysql_connect("localhost","blah","private");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("dbname", $con);
display.php file
<html>
<head>
<title>Html and PHP</title>
</head>
<body>
<!-- Form -->
<form action="process.php" method="post">
Username: <input type="text" name="username" >
Hardware ID: <input type="text" name="hardwareid" >
<input type="submit" >
</form>
</body>
</html>
process.php file
include_once("ur_file_dir/connection.php");
if ((isset($_POST['username']) && isset($_POST['hardwareid'])) {
$sql="INSERT INTO tablename(
Username,
HardwareID)
VALUES
($_POST['username'],$_POST['hardwareid'])";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record successfully added...";
mysql_close($con)
}

You should validate your input, ie:
if (!empty($_POST['username'] && !empty($_POST['hardwareid']) {
// do your insert here
}
Also, you should be wary of allowing user input to be inserted directly into your query, as this leaves your open to SQL injections. A better way to do this is to use PDO and prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php

Related

change from mySQL to SQL and now cant get record creation

I am running WAMP 2.5 on Win7 and created a webpage to insert records into a mySQL database. This worked perfectly.
Then I needed to use SQL Server 2014 (remote server on LAN) instead of mySQL (local in WAMP), and while everything seems ok, i am not getting the records created in the table, yet no error either.
Account used to log in with is db owner.
Any help would be great.
Thanks
Len
Code is as follow (I call sqlconnect.php for db connection) and get confirmation that connection was successful.
File is called insert-data.php so it calls itself if form is empty and Submit is selected.
<?php
if(!empty($_POST['mcpbarcode'])) {
header("Location insert-data.php");
include('sqlconnect.php');
$mcpbarcode = $_POST['mcpbarcode'];
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('$mcpbarcode')";
sqlsrv_query($conn,$sqlinsert);
if (!$sqlinsert) {
die('error inserting new record');
}
$newrecord = "New record added";
}
?>
<html>
<head>
<title> Insert Barcode into Database</title>
</head>
<h3><font color = red>This window must be open and active</font></h3>
<img src="header.jpg" alt="anyname" style="width:800px;height:165px;">
<body>
<h1> Insert barcode into Database</h1>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<label>Barcode:<input type="text" name="mcpbarcode" autofocus /></label>
<br /><br />
<input type="submit" value="Add new record" />
</form>
<?php
$newrecord="";
echo $newrecord
?>
</body>
</html>
See if it's working like that:
If mcpbarcode column is a string type (varchar, char etc):
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES ('".$mcpbarcode."')"
OR if mcpbarcode column is int, float, etc:
$sqlinsert = "INSERT INTO mcpbarcode (mcpbarcode)
VALUES (".$mcpbarcode.")"
but you should have an error on mysql also ...

Writing to database from CKEDITOR

I'm trying to write to a database using CKEditor.. when I press submit it dies and says localhost is currently unable to handle this request.
HTTP ERROR 500
I only want to save the textarea into a row in database so I can then read the row on to another page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Classic editor replacing a textarea</title>
<script src="http://cdn.ckeditor.com/4.6.0/standard-all/ckeditor.js"></script>
</head>
<body>
<form id="editor1" action="save.php" method="post" >
<textarea cols="80" id="editor1" name="editor1" rows="10">
</textarea>
<p>
<input type="submit" value="Submit">
</p>
</form>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</body>
</html>
PHP script
<?php
if(isset($_POST['submit']))
{
// Putting data from form into variables to be manipulated
$text = $_POST['editor1'];
$conn = mysql_connect("localhost","root","root") or die ("Can't connect");
mysql_select_db("managerMessage",$conn);
// Getting the form variables and then placing their values into the MySQL table
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
}
?>
You are not concatenating the value correctly in this statement and also text data in a query like this should be wrapped in quotes
mysql_query("INSERT INTO text (textarea) VALUES ("mysql_real_escape_string($text)");
This is a corrected verion of your code
mysql_query("INSERT INTO text
(textarea)
VALUES ('" . mysql_real_escape_string($text) . "')");
A simpler piece of code would be to read and probably maintain would be
$t = mysql_real_escape_string($text);
mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
I would be remiss if I did not remind you that
Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
EDIT RE: not saving the data to the database
Add some error checking to your code like so:
$t = mysql_real_escape_string($text);
$result = mysql_query("INSERT INTO text (textarea) VALUES ('$t')");
if ( ! $result ) {
echo mysql_error();
exit;
}
Once you know the error, if one exists, you can start work on fixing it.

Querying Radio buttons into MYSQL database

I need advice to use radio buttons in html to query into MYSQL base on the user selection.
The table is called "Trainers"
There are Three trainers:
krillavilla
Novac
Urie
The user choose what trainer he/she want to setup a meeting with. On the MYSQL I want to show the "krillavilla" got "5" meetings with users and "Urie" got "0" meetings with users.
I research this post:
How can i add radio buttons record into MySQL fields using PHP
but I was trying to avoid arrays
And on this post:
Inserting the selection of radio buttons into MySQL
Doesnt answer my question what I am looking for.
This is my php:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost","******","******","*****");//This is the login creditial
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());//Error check for execution
}
// Escape user inputs for security
$trainers = mysqli_real_escape_string($link, $_POST['trainers']);
// attempt insert query execution
$sql = "INSERT INTO trainers (trainers) VALUES ('$trainers')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="test2.php" method="post">
<p>
<input type="radio" name="trainers" id="krillavilla">krillavilla
</p>
<p>
<input type="radio" name="trainers" id="Urie">Urie
</p>
<p>
<input type="radio" name="trainers" id="Novac">Novac
</p>
<input type="submit" value="Submit">
</form>
</body>us
</html>
This is my second form page. I am trying to create a GYM schedule using three form webpages where the user will:
Sign up a membership=> User Select the trainer=> User selected what type of membership he/she wants=> confirmation page
but for now i need help of figuring out how can i get my radio buttons data to record how many users that assign to trainer on MYSQL.
BTW I used this:
http://www.tutorialrepublic.com/php-tutorial/php-mysql-insert-query.php
as my guide
you need to set value="Urie" instead of id="Urie"

Inserting form information with php to mysql does not work

I have a problem inserting information into a sql database.
The user needs to answer a question and submit that.
<!DOCTYPE html>
<html>
<head>
<title>Some title</title>
</head>
<body>
<form action="neg.php" method="post">
<b>Enter a title:</b><br /><input type="text" name"title" /><br />
<input type="submit" value="I !" />
</form>
</body>
</html>
The php page looks like this:
<?php
/* get all input*/
$connection = mysqli_connect("localhost","X","Y","Z") or die("Some error occurred during connection " . mysqli_error($connection));
$sql="INSERT INTO xyz (title)
VALUES
('$_POST[title]')";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "1 record added";
?>
Can anyone please help me out here? I'm really stuck, tried a million things, but simply do not see what went wrong. I also do not get an error, so I'm unsure what the problem is. Can anyone please help me out here?
Thanks in advance!
EDIT
OP changed INSERT INTO dislike to INSERT INTO xyz from an edit after my submitting this answer, including changing value="I don't want to see this show ever again!" to value="I !"
Original answer from original question:
The reason why your query is not working is because the = is missing in name"title"
Change it to name="title"
You should also consider using prepared statements or PDO.
The method you're using now, is open to SQL injection
I've made it a bit more safer for you doing it the following way:
<?php
/* get all input*/
$connection = mysqli_connect("localhost","X","Y","Z") or die("Some error occurred during connection " . mysqli_error($connection));
$title=mysqli_real_escape_string($connection,$_POST['title']);
$sql="INSERT INTO dislike (title) VALUES ('$title')";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "1 record added";
?>
HTML rewrite:
<!DOCTYPE html>
<html>
<head>
<title>Dislike series</title>
</head>
<body>
<form action="neg.php" method="post">
<b>Enter a title:</b><br /><input type="text" name="title" /><br />
<input type="submit" value="I don't want to see this show ever again!" />
</form>
</body>
</html>
Here are a few tutorials on prepared statements that you can study and try:
Tutorial one
Tutorial two
Tutorial three
Here are a few tutorials on PDO:
PDO tutorial one
PDO tutorial two
PDO tutorial three

variables go into db without being retrieved through $_POST

This works but How are the values of the variables being put into the db without retrieving them through the $_POST?
Is this something new in php5 or have I just never seen it used this way before?
<!doctype html>
<html>
<head>
<title></title>
</head
<body>
<form action="insert.php" method="post">
First Name: <input type="text" name="fname" /><br>
Last Name: <input type="text" name="lname" /><br>
Username: <input type="text" name="uname" /><br>
<input type="submit" name="submit" value="Register"/><br>
</form>
</body>
</html>
insert.php
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO traders (fname, lname, username)
VALUES
('$fname','$lname','$uname')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added " ;
mysqli_close($con);
?>
because you use here register globals option in php which is now deprecated/removed in new versions of php (mainly because of security issues) which translates $_POST['fName'] into $fName
you should always use $_POST/$_GET instead
read more: http://php.net/manual/en/security.globals.php
No, this is called Register Global and is DEPRECATED long time ago, one should never use this !
When on, register_globals will inject your scripts with all sorts of variables, like request variables from HTML forms. This coupled with the fact that PHP doesn't require variable initialization means writing insecure code is that much easier.
For more information:
http://php.net/manual/en/security.globals.php

Categories