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
Related
I have a piece of code which inserts user's input into a database:
Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("DB status: connection failed: " . $conn->connect_error);
} else {
echo "DB status: connected";
}
?>
<html>
<h1>Add data</h1>
<form method="post">
<p>Name: <input type="text" name="name"></p>
<p>Goals scored in:</p>
<p>14/15 <input type="text" name="14"></p>
<p>15/16 <input type="text" name="15"></p>
<p>16/17 <input type="text" name="16"></p>
<p>17/18 <input type="text" name="17"></p>
<button type="submit" name="save">save</button>
</form>
<?php
$sql = "INSERT INTO `goals` (`Name`, `14/15`, `15/16`, `16/17`, `17/18`) VALUES ('".$_POST["name"]."', '".$_POST["14"]."', '".$_POST["15"]."', '".$_POST["16"]."', '".$_POST["17"]."')";
$result = mysqli_query($conn,$sql);
?>
The problem is that when I load the page for the first time, it already sends 0's to the database. How can I prevent this from happening?
Thanks a lot for helping!
add an action to your form and use that to send the sql query. You should probably also be using form validation requiring some fields like name to be filled out.
<p>Name: <input type="text" name="name" required></p>
Calling a particular PHP function on form submit
Add this piece of code at the beginning to fix the issue:
if (isset($_POST['submit']))
{
}
I have a form page
<html>
<body>
<form action="insert.php" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
And this is the php page:
<html>
<body>
<?php
$con = mysql_connect("xxx","xxx","xxx");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname) VALUES('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
</body>
</html>
Now, I want it to display 1 record added on the same page as the form and not have the form send me to a new insert.php page with it. Basically, I want the submit form to stay in the same page with maybe a a new message popping up to show that it has worked.
I have already looked through some answers on stackoverflow like using
if(isset($_POST['SubmitButton']))
but it doesn't work. Maybe I placed it wrong or used it incorrectly but could someone help me figure it out?
Just make it an action to itself, and set an if $_POST['submit'] to add the records, and you can have both in the same file. If you wish to do so without refreshing the page, you'll need to use AJAX.
<html>
<body>
<?php
if (isset($_POST['SubmitButton'])) {
$con = mysql_connect("xxx","xxx","xxx");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$sql="INSERT INTO app (fname, lname)
VALUES
('$_POST[fname]','$_POST[lname]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="" method="post">
App Name: <input type="text" name="fname" /><br><br>
App ID: <input type="text" name="lname" /><br><br>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Also, mysql_* is deprecated, so you should consider converting to PDO or MySQLi to avoid SQL injection!
I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
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.
I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");