Given the following HTML form:
<form id="form1" name="form1" method="post" action="comments.php">
<textarea name="text" id="textarea" cols="45" rows="5"></textarea><br/>
<input type="submit" name="button" id="button" value="Update" />
</form>
...and the following PHP code (comments.php):
<?php
require("includes/config.php");
$fromtextarea = $_POST['text'];
$con = mysql_connect($dbserver, $dbusername, $dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname , $con);
$sql = "INSERT INTO textarea (comment) VALUES ('$fromtextarea')";
if (mysql_query($sql)) {
header("Location: home.php");
}
else
echo "no no no";
mysql_close($con);
?>
How can I get the data and display all user comments on a page?
Take a look at SELECT sql statement. Your query should look like something like this:
SELECT comment FROM textarea;
Then see how to manipulate the result with mysql_fetch_* functions in PHP (http://www.php.net/manual/fr/function.mysql-fetch-assoc.php).
By the way, mysql_* functions are deprecated (and will be deleted soon). I advise you using mysqli_* functions (http://www.php.net/manual/fr/book.mysqli.php) or (better) PDO (http://php.net/manual/fr/book.pdo.php).
Do like this
$sql = "INSERT INTO textarea (comment) VALUES ('". $_POST["text"] . "')";
Make sure you sanitize it before using it in your query.
Related
I want to go from a HTML form to a SQL database using PHP.
Here is my current code:
PHP:
if(isset($_POST['submitIpG']))
{
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ($_POST['submitIpG'])";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
echo "<br />\n";
}
As you can see it's hard coded with a specific IP. However, I want it to use an IP from the user input in my form.
HTML:
<form method="post">
<input type="value" name="submitIpG" value=""/>
<input type="submit" name="submitIpG" value="ADD"/>
</form>
How do I do this? I've tried things such as:
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpB']')";
Without success.
Thanks!
You should set the action php script in form html also your inputs should be like
<form method="post" action="your_php_file.php">
<input type="text" name="submitIpG" placeholder="the ip input"/>
<input type="submit" name="submit" value="ADD"/>
</form>
and your_php_file.php should be like
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpG']')";
But the most important part is DO NOT USE sql queries like that. Please consider using prepared statement.
There is a good and simple example at w3school. this is the link you may want. https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Im trying to add a new user name to mysql table throw wordpress. But everytime I try to do it, I have no error message, but there are no lines added to the data base.
This is the wordpress page with the php inside:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
$sql="INSERT INTO `Users` (`sName`, `sEmail`)
VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
?>
I can't see whats wrong. I think it may be something wrong with the connection. Any ideas?
Thank you!
Edit
As suggested, Im trying to use $wpdb so I've created a php file in a folder call my-codes (at the same level of wp-admin, wp-content and wp-includes) and I added the following code to a file call insertUser.php:
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"sName" => $sName,
"sEmail" => $sEmail));
?>
Now in my page Im trying to call this function and Im doing this:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
if(isset($_POST['Submit']))
{
include("./my-codes/insertUsers.php");
}
?>
And im still not being able to insert any row in the database. Any suggestions?
EDIT
I needed a pluggin to actually connect my sql database with wordpress. The code is correct.
Replace your code with the code that i have provided.
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root"); // ensure that your password in empty or root in your localhost
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
if(isset($_POST['Submit']))
{
// Previous Insert Query which has discrepency in form input names and Insert Values
//$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
// My new Query with corrected form input names for Input Values during POST.
$sql = "INSERT INTO `Users`(`sName`, `sEmail`) VALUES ('".$_POST['Name']."','".$_POST['Email']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
}
Finally have a check at the table field Names and my code works fine hope it will serve you to.
use the query like this one to make thing happen,
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('".$_POST['sName']."','".$_POST['sEmail']."')";
for preventing from injection you can use this way to build query.
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('$name','$email')";
using prepared statement
$mysqli = new mysqli("example.com", "user", "password", "database");
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$stmt=$mysqli->prepare("INSERT INTO `Users` (`sName`, `sEmail`) VALUES (?,?)");
$stmt->bind_param("ss", $name,$email);
$stmt->execute();
for detailed on prepared statement got to http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I've done a php script that will create a title and a text and load it to my database(mysql). When i press submit the script runs and create 1 row right and then like 3-5 empty rows.
The same thing happens when i refresh the page(empty form), 2 new empty rows shows in my database?
How do i solve it?
<?php
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
<form method="post" onSubmit=window.location="index.php">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/> <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10">
</textarea><br/>
<input type="submit" value="Publicera nyhet">
</form>
Your INSERT query is executing every time when page loads, set a POST variable to check whether the form has been submitted or not and why you are using event attribute window.location for submitting form, you can simply use action attribute and set that value either blank or the file name where you want to send your data.
<form action="" method="post">
OR
<form action="index.php" method="post">
Your date variable is also wrong. To generate date into YYYY-MM-DD format write like below
$date = date('Y-m-d');
Your script may like this
if(isset($_POST['submit'])) {
your post variables and insert query goes here
}
You can also insert a hidden input field into your form tag like so
<form action="" method="post">
<input type="hidden" name="save" value="details">
other HTML code goes here
</form>
in that case you test the post variable like this
if(isset($_POST['save']) && $_POST['save'] === "details") {
your post variables and insert query goes here
}
First learn the basic concept about PHP from http://www.php.net/ and search for appropriate question over here before asking any question.
Wrap your php code around condition to check if the form is submitted or not. Like:
<?php
if(isset($_POST['submit')){
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
Always catch form submission. You can use isset() with this:
<?php
$con = mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Y-m-d"); // put the correct format on the date
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '$date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header('Location: index.php'); // always redirect
}
?>
<form method="post" action="">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/><textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea><br/>
<input type="submit" name="submit" value="Publicera nyhet" />
<!-- ^^ add a name -->
</form>
You should check if $_SERVER['REQUEST_METHOD'] is POST and only then run the INSERT statement.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
I have created a simple login and registration project.
The user is then presented with their 'Profile Page'. I want them to be able to click an 'edit' button and type information into fields that were not present during registration. I can get the script to add a 'bio' to the database but it creates a new record, How can I add this bio info to a particular members record?
<?php
ob_start();
session_start();
if(!isset($_SESSION['Email'])){
header("Location: login.php");
}
?>
<body>
<div id="wrapper">
<?php
$con = mysql_connect("HIDDEN");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("HIDDEN", $con);
$sql="INSERT INTO members (Bio)
VALUES
('$_POST[Bio]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
<form action="edit.php" method="post">
Bio: <input type="text" name="Bio">
<input type="submit">
</form>
</div>
</body>
</html>
If the bio column is in the same table, then you need to perform an UPDATE statement, not another INSERT statement. You also need to know the user’s ID.
UPDATE `members` SET `bio` = ?
Also, don’t use $_POST variables directly in an SQL statement. You’re leaving your site vulnerable to SQL injection vulnerabilities then. Use something like PDO to prepare statements and then execute them with bound parameters. An example, where $db in an instance of PDO:
$sql = "UPDATE `members` SET `bio` = :bio WHERE `id` = :id LIMIT 1";
$statement = $db->prepare($sql);
$statement->bindParam(':bio', $bio);
$statement->bindParam(':id', $user_id);
$statement->execute();
You’ll need to assign the $bio and $user_id variables.
<?php
ob_start();
session_start();
if(!isset($_SESSION['Email'])){
header("Location: login.php");
}
?>
<body>
<div id="wrapper">
<?php
if(isset($_REQUEST['submit'])) {
$con = mysql_connect("HIDDEN");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("HIDDEN", $con);
$sql="INSERT INTO members(Bio) VALUES ('".$_POST['Bio']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
<form action="edit.php" method="post">
Bio: <input type="text" name="Bio">
<input type="submit" name="submit">
</form>
</div>
</body>
</html>
I am trying to submit the page to itself but some reason the following code is not working. Also How can I get the table1 primary key ID back after inserting the data successfully? I have a child table which needs this ID. Thanks for any suggestions.
<?php
include('db_login.php');
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
if ($_POST['Submit'])
{
$first = $_POST["first"];
$first = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($first): $first);
$last = $_POST["last"];
$last = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($last): $last);
$insertsql = "INSERT INTO table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
}
?>
<form name="hotlineForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<input id="first" type="text">
<input id="last" type="text">
<input type="submit" value="Submit"></form></body>
What part isn't working on the post back? Are you not entering your if statement?
To get the ID of the last insert use the following after your $result1 = mysql_query(...):
$primary_id = mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Change your form inputs to include name attributes. Without them, your $_POST will be empty.
<input name='first' id="first" type="text">
<input name='last' id="last" type="text">
<input name='Submit' type="submit" value="Submit">
As mentioned in the comments, get_magic_quotes should not be used. You've correctly called mysql_real_escape_string() on your inputs already.
Following your insert, get the id from mysql_insert_id():
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = myqsl_insert_id();
if ($_POST['Submit'])
I don't see a form element with this name.
try:
if (isset($_POST['first']) && isset($_POST['last']))
For getting inserted ID you can use:
mysql_insert_id();
You are missing a closing } here:
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
} <<---- Close your if statement here.
if ($_POST['Submit'])
Currently the code that does the actual work only gets called if the DB cannot be selected.
Not very useful.
This is why proper indentation is important.
If you are religious about your indentation, you will spot these kind of errors instantly.
Use a name for the input field and check if it was sents not the submit