This question already has answers here:
Quickest way to check for pre-existing record before insert [mysql_errno()]
(2 answers)
Closed 9 years ago.
I am using the following PHP code to store data in my MySQL database, everything works perfect but I would like to build in a check; if the email already exists in the database then redirect to another page. (I'm a rookie when it comes to PHP)
<?php
if(empty($_POST['name']))
{} else {
define('DB_NAME', 'dbname');
define('DB_USER', 'dbuser');
define('DB_PASSWORD', 'dbpass');
define('DB_HOST', 'host');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) { die('could not connect: ' . mysql_error()); }
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) { die('can not use ' . DB_NAME . ': ' . mysql_error()); }
$sql="INSERT INTO game (name, lastname, company, email, time) VALUES
('".$_POST['name']."','".$_POST['lastname']."','".$_POST['company']."','".$_POST['email']."','".$_POST['time']."')";
if (!mysql_query($sql)) { die('Error: ' . mysql_error()); }
mysql_close();
}
?>
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
exit('Invalid email address'); // Use your own error handling ;)
}
$select = mysqli_query($connectionID, "SELECT `email` FROM `game` WHERE `email` = '".$_POST['email']."'") or exit(mysqli_error($connectionID));
if(mysqli_num_rows($select)) {
exit('This email is already being used');
}
Stick that in above the insert query
First, to your question. The most simple is to use the header() function to redirect to a page.
if ( !$email) {
header('Location: http://example.com/new_page.html' );
} else {
// Continue with code
}
Secondly, there is a whole lot of issues going on in that code. For example:
Use PDO
parameterize your query
Your control statement should probably look like if(!empty($_POST['name'])) {
Related
I need to connect an html form to my sql database and I'm starting out with a simple form so I can understand how it works. I can't figure out what I am doing wrong. I have the form created, the php script, and the database created. Whenever I submit the form it takes me to a blank page and nothing has been added to my database. I've written error messages if the connections fail but I'm not seeing those either. I'm not as advanced in programming can someone please help me?
index1.html
<html>
<body>
<form action="info.php" method="post">
<p>Username:<input type="text" name="username" /></p>
<p>Email:<input type="text" name="email" /></p>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
info.php
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
//connection to host
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//error if not connected to host
$db_selected = mysql_select_db(DB_NAME, $link);
//select the database
if(!$db_selected){
die('Can\'t use ' . DB_NAME . ':' . mysql_error());
}
echo 'Connected successfully';
$value = $_POST['username'];
$value2 = $_POST['email'];
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
//error check to see if connected to tables
mysql_close();
//close connection
?>
As I stated in comments; your mysql_ code checks out, so chances are you need to use either mysqli_ or PDO, since mysql_ functions may very well not be available for you to use.
If the following mysqli_ rewrite does not work for you, then the problem goes deeper and would be out of scope of the question.
Using error reporting will/should confirm that. Consult "Footnotes" on how to use it in your PHP file(s).
<?php
define('DB_NAME' , 'users' );
define('DB_USER' , 'root');
define('DB_PASSWORD' , '');
define('DB_HOST' , 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//connection to host
if (!$link) {
die('Could not connect: ' . mysqli_error($link));
}
echo 'Connected successfully';
$value = mysqli_real_escape_string($link,$_POST['username']);
$value2 = mysqli_real_escape_string($link,$_POST['email']);
$sql = "INSERT INTO guests (username, email) VALUES ('$value', '$value2')";
if(!mysqli_query($link, $sql)){
die('Error: ' . mysqli_error($link));
}
//error check to see if connected to tables
else{
echo "Data entered";
}
mysqli_close($link);
//close connection
?>
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
Error reporting: http://php.net/manual/en/function.error-reporting.php
Footnotes:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Make sure your server is running and properly configured for PHP/MySQL/Apache.
Make sure your columns are indeed VARCHAR and long enough to accommodate the data.
Try this query:
INSERT INTO guest set username=$value1,email=$value2
hope it will solve .
Try this, it should work for you.
$sql = "INSERT INTO guests (username, email) VALUES (".$value.", ".$value2.")";
I'm trying to add an announcement with the need of the user [ id] who posted it and I was going to take it via session I don't know its not working I keep getting this error (Fatal error: Cannot redeclare check_login() (previously declared in C:\xamppp2\htdocs\session.php:17) )
and I'm trying to insert current time and date separately is (date(),now()) are the right functions? I'm trying to insert those too, could you guys possibly help? here's my code
I included the session on top of my page
<?PHP include('session.php');?>
and here's the rest of my php file
<?PHP
$link = mysql_connect('localhost','root','');
if (!$link) {
die('Could not connect :' . mysql_error());
}
$Selected= mysql_select_db("elearningg", $link);
if (!$Selected) {
die("Could not connect: " . mysql_error());
}
if(!empty($_POST))
{
$msg = '';
$error = '';
$title = $_POST['title'];
$desc = $_POST['desc'];
if(trim($title) == '')
{$error = 'Please enter event title';}
else if(trim($desc) == '')
{$error = 'Please enter description ';}
$IID =$_SESSION['userid'];
if($error=='') {
$qry6="INSERT INTO announcement (`Atitle`,`Adescription`,`Adate`,`Atime`,`IID`) VALUES
('$title','$desc',date(),now(),$IID)" ;
$result6=mysql_query($qry6);
$msg = " Announcement is added ";
}
}
mysql_close($link);
?>
and here's my actual session script..
if (!$link) {
die('Could not connect :' . mysql_error());
}
$Selected= mysql_select_db("elearningg", $link);
if (!$Selected) {
die("Could not connect: " . mysql_error());
}
ob_start();
session_start();
function check_login(){
if(!empty($_SESSION['userid'])){
return 1;
}else{
return 0;
}
}
?>
This isn't a session problem. You are as your error message says trying to redeclare check_login().
You can only declare a function once.
So depending on how your files are structured you need to make sure that that function is only declared once. Perhaps you use includes in your files. You either need to make sure it isn't redeclared so think about how you structure it so that doesn't happen or use require_once, this adds more overhead to your script though.
http://php.net/manual/en/function.require-once.php
I have a simple html form and a php file to execute a database insertion. The problem I am having is that when I press the submit button, my database table receives 3 copies of the same submission and I only need one. Below is the code.
html:
<!DOCTYPE html>
<html>
<form action="demo.php" method="post">
<p>
Input 1: <input type="text" name="input1" />
<input type="submit" value="Submit" />
</p>
</form>
</html>
php:
<?php
define('DB_NAME', 'phpmyadminName');
define('DB_USER', 'phpmyadminUser');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
$sql = "INSERT INTO demo (input1) VALUES ('$values')";
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
The DB_NAME, DB_USER, and DB_PASSWORD have all been changed for obvious reasons, but the code does work.
It just submits too many copies of the form data to the database table. Way back when I was in school, I had this issue, but it seemed like the problem was on the server's end and not our code. The server used here is mine and I do have full control over it. If the server is the issue at fault, I need help correcting that (as I am doing this to learn how to admin these tools, I do not know much more than basic level administration).
Kenneth, the code you have provided here honestly needs some work. First of all, please don't use the mysql API anymore. It's deprecated, will no longer be supported in future PHP versions, and is insecure. For all database operations use the mysqli or PDO API's, preferrably with prepared statements.
Secondly, do not ever INSERT $_POST or $_GET variables directly into the database without validating/sanitizing them first as someone could delete your data or even worse your whole database. PHP has numerous functions to make this very easy such as ctype depending on the data type.
Maybe try something like this in your code:
if (!empty($_POST['input1'])) { //checks if data was received//
$value = $_POST['input1'];
mysql_real_escape_string($value);
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
} else {
echo "form was not received";
exit;
}
I also noticed that your variable names were different, which is corrected above.
EDIT :
Mistakenly used wrong syntax for PHP ctype function.
You are taking the POST input value in the variable named $value and in query you are sending $values
I have corrected the code.
Can you please try the below code
<?php
define('DB_NAME', 'phpmyadminName');
define('DB_USER', 'phpmyadminUser');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['input1'];
if($value!=''){
$sql = "INSERT INTO demo (input1) VALUES ('".$value."')";
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
Below is correct code for the issue. I have checked that when you refresh your page it will create new blank entry in database and also the variable name is wrong.
You have to check for the Request method. This
$_SERVER['REQUEST_METHOD'] === 'POST'
will check the form method and it will prevent the blank entries in database.
<?php
define('DB_NAME', 'test');
define('DB_USER', 'root');
define('DB_PASSWORD', 'mysqldba');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
//Test for request method
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$value = $_POST['input1'];
$sql = "INSERT INTO demo (input1) VALUES ('$value')";
//echo $sql;die;
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
}
mysql_close();
?>
Okay I have been using mysql for use with my website however it has not been going well with some of the syntax. I've read up on it but I fell like I'm still doing it wrong... In the picture below, I have defined database variables and then tried to log into my database containing the columns of "ID" "Username" and "Password". I then define the username and password input, from my form, in the php and asked the database to compare... am I missing something? I feel like it's not comparing the data from the form with the data in the database. It works even if I type the password wrong..
//Name of File: LoginCheck.php <--Called with the Login.php (which has a form on it)
//posts information to LoginCheck.php
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'blah');
define('DB_PASS', 'blah');
define('DB_NAME', 'Profiles');
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if(!$con){
die('Could not connect. ' . '<br/>' . 'Error: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $con);
if(!$db_selected){
die('Could not select database: ' . DB_NAME . '<br/>' . 'Error: ' . mysql_error());
}
//defines login variables from the form.
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$login = mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
echo 'Error: ' . mysql_error();
echo "Didn't log in. Not matching database intel.";
}else{
echo "Logged in matching database intel.";
}
mysql_close($con);
?>
mysql_query() just returns a resource. You can then use that resource to get that data or more information about the query.
You can use mysql_num_rows() to see if your query was successful:
if(!mysql_num_rows($login)){
FYI, you should not be storing passwords in plain text. That is a huge security no-no.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
It should be:
$login = mysql_query("SELECT * FROM Users WHERE Username = '$username' AND Password = '$password'", $con);
if(!$login){
echo 'Error: ' . mysql_error();
} elseif (mysql_num_rows($login) == 0) {
echo "Didn't log in. Not matching database intel.";
}else{
echo "Logged in matching database intel.";
}
Not finding a match is not the same as an error.
Does anyone know to give my user account access to a table? I connect to the database fine but when I try to select the table it tells me Access denied for user 'dboxxxxx'#'%' to database.
I'm using basic php code
$con = mysqli_connect('xxxxxx.db.1and1.com', 'xxxxx', 'xxxxxx');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
else {echo 'success!';}
$selected = mysqli_select_db($con,'userTable');
if(!$selected){
die ('cannot use db: '.mysqli_error($con));
}
There is no permissions options on the 1and1 phpmyadmin that I can see unless I'm totally missing it. Anyone have any ideas?
First of all, you need to supply dboxxxxx as a username, not 'dboxxxxx'#'%'
Are you running this code localy or within your server? The 1und1 firewall blocks connections from the foreign networks
You're probably not making the connection to the database correctly.
Try the changes I made. Note that I do not know that you are using classes and functions.
UPDATE
$mysqli = new mysqli('xxxxx.db.1and1.com', 'xxxx', 'xxxx','xxxx');
if(mysqli_connect_errno ())
{
printf('Unable to connect to database ' . mysqli_connect_error());
}
else
{
$stmt = $mysqli->stmt_init();
if(!$stmt)
{
echo "init failed";
}
else
{
$cmd = "insert into `userTable` (`oauthtoken`,`oauthtokensec`,`userid`,screenname`) VALUES ('?','?','?','?')";
if($stmt->prepare($cmd))
{
$stmt->bind_param('1','1','1','1');
$stmt->execute();
echo $stmt->affected_rows . " Row(s) Inserted";
$stmt->close();
}
else
{
echo "Prepare Failed";
}
} $mysqli->close();
}