I've been trying to accomplish this, but as other issues I just can't figured it out. I've been reading around for posibles solutions but non of them goes along with my code, or if they do I can't figure out how or where to use them.
I have a DB where a user sends records. The database consist in few tables containing the Following "Name, Lastname, Phone". If any of this values is duplicate, I would like my code to identify and Ignore the submission of the Form if ALL this VALUES already exist on the DB.
Here is my code:
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$_POST[Name]','$_POST[LastName]','$_POST[Phone]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
mysql_close($con);
?>
The mysql_* function are all deprecated now, and should NEVER be used. change your code to do something like the following:
//Set up a PDO connection to MySQL
$host = 'host_name';
$dbname = 'database_name';
$user = 'user_name';
$pass = 'user_pass';
try
{
$DB = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
//Determine whether the appropriate values have been passed.
if(isset($_POST['Name']))
{
$name = $_POST['Name'];
}
else
{
echo "You must provide a name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['LastName']))
{
$name = $_POST['LastName'];
}
else
{
echo "You must provide a last name!";
exit; //This may not be what you want to do here, it's an example action
}
if(isset($_POST['Phone']))
{
$name = $_POST['Phone'];
}
else
{
echo "You must provide a phone number!";
exit; //This may not be what you want to do here, it's an example action
}
//Set up the query using anonymous values
$sql="INSERT INTO people (Name, LastName, Phone) VALUES ('?','?','?')";
$sth = $DB->prepare($sql);
try
{
//Attempt to execute the insert statement
$sth->execute(array($_POST[Name], $_POST[LastName], $_POST[Phone]));
echo "Record Added";
}
catch(PDOException $e)
{
//If the insert failed, then you can handle the error, and determine
//what further steps need to be taken.
echo "Record Not Added";
}
Here's another question with a similar setting, that may also be useful to you:
https://stackoverflow.com/a/10414922/1507210
search in the table before insert
<?php
$con = mysql_connect("HOST","USER","PASS");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdb", $con);
$name = mysql_real_escape_string($_POST[Name]);
$LastName= mysql_real_escape_string($_POST[LastName]);
$Phone= mysql_real_escape_string($_POST[Phone]);
$search_res=mysql_query("SELECT * from people where Name='$Name' OR LastName='$LastName' OR Phone='$Phone'");
if(mysql_num_rows($search_res) < 1){
$sql="INSERT INTO people (Name, LastName, Phone)
VALUES
('$Name','$LastName','$Phone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Record Added";
}else{
echo "User Already exits";
}
mysql_close($con);
?>
Try this easy solution
$result = mysql_query("SELECT * FROM TABLE WHERE Column = 'value' ");
if( mysql_num_rows($result) < 1) {
mysql_query("INSERT INTO table (column) VALUES ('value') ");
}
Related
I'm using MAMP an my PHP won't add data to the db
I have looked at other similar questions and done everything on them, yet it still is not working.
I am using MAMP and I've done everything right as far as I know but the problem is the same no matter what I do.
<?php
require_once('dbconnect.php');
$email = $_GET['email'];
$name = $_GET['name'];
$message = $_GET['message'];
$my_query = "";
$my_query = "select * from Users where email = '$email' ";
$my_query = "INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')";
$result = mysqli_query($connection, $my_query );
if($result)
{
echo "Successfully Sent!";
}
else
{
echo "<b>ERROR: unable to post </b>";
}
}
mysqli_close();
?>
Here use this code and and tell what is the error
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Users (email, name, message) VALUES ('$email', '$name', '$message')"))
{
echo("Error description: " . mysqli_error($con));
}
mysqli_close($con);
?>
if you dont get any error or blank value in db use your values like
values('".$email."', '".$name."', '".$message."')"
in db It will be executed like values('test.abc.com', 'abc', 'It is working')
I have this script, but i don't know what could be wrong here when I hit "post" button on the main page. Where the error can come from?
The page script:
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql="INSERT INTO message (messages, user, picture, date_created, poster)
VALUES
('$messages','$user','$pic','".strtotime(date("Y-m-d H:i:s"))."','$poster')";
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$user'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header("location: lol.php");
exit();
$name=$_POST['name'];
$pic=$_POST['name1'];
mysql_query("UPDATE messages SET picture = '$pic' WHERE FirstName='$name'");
?>
This is the dbconnect file:
$con = mysql_connect("hostname","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("asl", $con);
?>
Ensure you have selected your db using mysql_select_db
mysql_connect('hostname','username','password') or die("not able to connect");
mysql_select_db('myDatabase');
And mysql_ extensions are deprecated.. Dont use it
this errors seems to be caused by either selecting wrong database or not selecting it.
check dbconnection.php and for this line in it
mysql_select_db("your_database_name",$your_connection);
See whether this line is present and pointing to database or not and make sure this databse exists
Update It seems that your file is not being included try require() so that it produces fatal error and you can see file s being including or not
require("dbconnection.php"); // will produce fatal errors
First of all mysql_connect is outdated and unsecure, better use PDO instead
<?php
session_start();
include("dbconnection.php");
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$messages = clean($_POST['message']);
$user =clean($_POST['name']);
$pic =clean($_POST['name1']);
$poster =clean($_POST['poster']);
$sql = $db->prepare("INSERT INTO message (messages, user, picture, date_created, poster) VALUES (:messages, :user, :picture, :date_created, :poster)");
$sql->bindParam(':messages', $messages);
$sql->bindParam(':user', $user);
$sql->bindParam(':picture', $pic);
$sql->bindParam(':date_created', strtotime(date("Y-m-d H:i:s")));
$sql->bindParam(':poster', $poster);
$stmt = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :user");
$stmt->bindParam(':picture', $pic);
$stmt->bindParam(':user', $user);
$stmt->execute();
if (!$sql->execute())
{
die('Error: ' . mysql_error());
}
$name=$_POST['name'];
$pic=$_POST['name1'];
$stmt_2 = $db->prepare("UPDATE messages SET picture = :picture WHERE FirstName = :name");
$stmt_2->bindParam(':picture', $pic);
$stmt_2->bindParam(':name', $name);
$stmt_2->execute();
header("location: lol.php");
?>
This is the dbconnect file:
<?php
//Connect to sql db
try {
$user_db = "username";
$pass_db = "password";
$db = new PDO('mysql:host=localhost;dbname=asl', $user_db, $pass_db);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
If the value of the result is 0 it has to go to 'cid_check_firstdep.php' otherways (if its 1) it has to go to 'cid_check_depwid.php'.
It has to work, but i don't know why it doesn't. I've tried what i could that i think would be possible to fix it, but nono.
Code:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
if ($sql<'1')
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>
or do i have to use :
if ($sql=='0')
?
|||
#John Conde
<?php
if(! get_magic_quotes_gpc() )
{
$withdraw = addslashes ($_POST['withdraw']);
}
else
{
$withdraw = $_POST['withdraw'];
}
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$__sql = "SELECT cardvalue FROM users WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($__sql,$con);
if ($__sql<'5000000')
{
header('Location: /ucp/includes/withdraw_fail.php');
mysql_close($con);
}
else
{
$_sql = "UPDATE users SET Bank=Bank + '$deposit' WHERE Username='".($_SESSION['username'])."'";
mysql_select_db("server");
mysql_query($_sql,$con);
$sql = "UPDATE users SET cardvalue=cardvalue +- '$deposit', thismonth_withdraw=thismonth_withdraw + '$deposit', lastwithdraw = Now() WHERE username='".($_SESSION['username'])."'";
mysql_select_db("bluecard");
mysql_query($sql,$con);
mysql_close($con);
header('Location: /ucp/includes/withdraw_done.php');
}
?>
You're checking the wrong variable for your SQL result. You're using the variable containing your query instead of the variable you never assigned to capture the result of mysql_query(). You also want to use mysql_num_rows() to see how many results were returned.:
$result = mysql_query($sql,$con);
if ($result && mysql_num_rows($result) == 1) {
FYI, you shouldn'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.
Hi Morgan I change your code according to my knowledge. I think this will help you to work done.
If you found any match to the username "count($return_data)" will get 1.
Thanks.
<?php
$con = mysql_connect("localhost","root","password");
$select_db = mysql_select_db("bluecard");
if (!$con)
{
die('Could not connect: ' . mysql_error());
header('Location: /ucp/error.php');
}
$sql = "SELECT validated FROM users WHERE username='".($_SESSION['username'])."'";
$query = mysql_query($sql,$con);
$return_data = array();
while($rows = mysql_fetch_array($query)){
$return_data[]=$rows;
}
if (count($return_data)<=1)
{
mysql_close($con);
header('Location: /ucp/cid_check_firstdep.php');
}
else
{
mysql_close($con);
header('Location: /ucp/cid_check_depwid.php');
}
?>
How do I use "emailaddress" as the only duplicate entry that provides a error?
A lot of the answers I've found use mysql_query but I want to use mysqli.
<?php
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
WARNING! the posted code and this answer (as i am only addressing the question now) contain big SQL injection leaks. Please read up on SQL injection and use escaping or prepared statements.
<?php
$con = mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$existsQuery = "select count(*) as count from entry where emailaddress like '".$_POST[emailaddress]."'";
$existsResult = mysqli_query($con, $existsQuery);
if($existsResult->fetch_object()->count > 0)
{
echo "email already exist";
}
else
{
$sql = "INSERT INTO entry (firstname, lastname, emailaddress, favoritesong) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[emailaddress]','$_POST[favoritesong]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
mysqli_close($con);
?>
simply make emailaddress unique in your table.
I am trying to convert my mysql command to fit the new standard of mysqli and I will post the scripts and then the questions. I already created the table in the database.
config.php:
$dbhost="databasehost";
$dbusername="username";
$dbpassword="password";
$dbname="databasename";
$connect = mysql_connect($dbhost, $dbusername, $dbpassword);
mysql_select_db($dbname,$connect) or die ("Could not connect to database");
?>
insert.php:
include("config.php");
if (isset($_POST[firstname]) && isset($_POST[lastname]) && isset($_POST[age])) {
$sql = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
mysql_query($sql, $connect);
header("Location: add.htm");
// "1 record added";
}
else {
echo "no record added";
}
if (!mysql_query($sql,$connect))
{
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
view.php:
<?php
include("config.php");
$sql = mysql_query("SELECT * FROM Persons");
if ($sql) {
while($results = mysql_fetch_array($sql)) {
echo $results['FirstName'] . ', ' . $results['LastName'] . ', ' . $results['Age'] . '<br/>';
}
} else {
die('Error: ' . mysql_error());
}
mysql_close($connect);
?>
First, how do I modify the scripts to use the mysqli instead of mysql?
Second, when using the above script, when I add something from the
form it always add duplicate entry. How do I prevent that?
Third, to prevent sql injection what can I add to the code? I know
for php attach I can use "$firstname =
trim(strip_tags(stripslashes($_POST['firstname'])));" Will that also
cover sql injection since I am sanitizing the input?
kindly read through the official manual for the migration :
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi