Check if email already exists in database and add/change data - mysql

I've got a form which has 14 numeric inputs and 2 text inputs - name and email. Someone is adding data and it's saved to the database - I've done it. But when someone is adding data for the second time using the same email address, database should override the data in specific row with that email.
I read about UPDATE in sql but I don't know how to make a query which will check if that email exists and after that add or update data.
<?php
$servername = "localhost";
$username = "username";
$password = "pass";
$dbname = "test";
$quantity = $_POST['quantity'];
$quantity2 = $_POST['quantity2'];
$quantity3 = $_POST['quantity3'];
$quantity4 = $_POST['quantity4'];
$quantity5 = $_POST['quantity5'];
$quantity6 = $_POST['quantity6'];
$quantity7 = $_POST['quantity7'];
$quantity8 = $_POST['quantity8'];
$quantity9 = $_POST['quantity9'];
$quantity10 = $_POST['quantity10'];
$quantity11 = $_POST['quantity11'];
$quantity12 = $_POST['quantity12'];
$quantity13 = $_POST['quantity13'];
$quantity14 = $_POST['quantity14'];
$name = $_POST['name'];
$email = $_POST['email'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "Saved.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Use insert . . . on duplicate key update. You can do this if you have a unique key on what you want to be unique:
create unique index idx_results_name_email (name, email);
Then, the database will enforce uniqueness. The statement you want is:
INSERT INTO Results (1paracwierc, 1paracwierc2, 2paracwierc, 2paracwierc2, 3paracwierc, 3paracwierc2, 4paracwierc, 4paracwierc2, 1parapol, 1parapol2, 2parapol, 2parapol2, final, final2, name, email)
VALUES ($quantity, $quantity2, $quantity3, $quantity4, $quantity5, $quantity6, $quantity7, $quantity8, $quantity9, $quantity10, $quantity11, $quantity12, $quantity13, $quantity14, '$name', '$email')
ON DUPLICATE KEY UPDATE 1paracwierc = VALUES(1paracwierc),
1paracwierc2 = VALUES(1paracwierc2),
. . .
final2 = VALUES(final2);

Related

I have an SQL syntax error when inputing data

I'm a beginner programmer and I'm getting a problem that I cannot seem to overcome. I predict it's a small syntax error but I don't know.
The code I'm using is the following:
<?php
$x=$_POST['firstname'];
$y=$_POST['lastname'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname="db1";
//Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
//Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "INSERT INTO 'user' ('fname', 'lname') VALUES ('$x','$y')";
if ($conn->query($sql) === TRUE) {
echo "New record created succesfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Once I press submit to input the data the following error comes up:
Connected successfullyError: INSERT INTO 'user' ('fname', 'lname') VALUES ('rty','rty')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''user' ('fname', 'lname') VALUES ('rty','rty')' at line 1
Any help? Thanks in advance.
update your query replace single quote(') from table name and column name with (`), Like
$sql = "INSERT INTO `user` (`fname`, `lname`) VALUES ('$x','$y')";

how to add name number email id to my mysql database

i have created a website with shared hosting from a company and i have created themes and fronted end development is completed. now the problem is
If some one visited my site and entered their details in temple having name, mail,number.
So how i can see those name and email and number in my mysql database.
I have installed mysql database.
Assuming visitors already have filled a HTML <form> element and data are inserted into the database, you will need to execute a SELECT statement to get the visitors details.
SELECT name, mail, number FROM [tableName]
Here's a PHP example :
<?php
$host = "127.0.0.1";
$user = "myuser";
$pass = "mypass";
$bdd = "mydatabase";
try {
$objBdd = new PDO("mysql:host=$host; dbname=$bdd; charset=utf8", $user, $pass) ;
$objBdd->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
} catch(Exeception $prmE) {
die('Error : ' . $prmE->getMessage()) ;
}
$getMyVisitors = $objBdd->query("SELECT name, mail, number FROM myTable");
while ($visitorData = $getMyVisitors->fetch()) {
echo "----\r\n";
echo "Name : " . $visitorData['name'] . "\r\n";
echo "Mail : " . $visitorData['mail'] . "\r\n";
echo "Number : " . $visitorData['number'] . "\r\n";
echo "----\r\n";
}
$getMyVisitors->closeCursor();
$objBdd = NULL;
Every statements using dynamic user data (example: username, password, comments ...) should be prepared.
If you want to use a WHERE condition, use prepared statements like
$getMyVisitors = $objBdd->prepare("SELECT name, mail FROM myTable WHERE number = ?");
$getMyVisitors->execute(array("+33000000000"));
Now, if the visitors informations are not saved in the database, you will need to create a HTML form element.
Your HTML form element should looks like :
<form action="myScript.php" method="POST">
<input type="submit" value="Send my informations">
</form>
Where myScript.php is a PHP script that will save the visitor's informations into the database. Use my example above to make that script, you will need to use an INSERT statement.
You will need to add input elements in the form as much as you need, in your case, three (name, mail, number).
Note that you will need to set the name attribute to each of your inputs to be able to get the inputs value in your PHP.
Example : <input type="email" name="visitorMail"> goes with $myVisitorMail = $_POST['visitorMail'];.
You Could directly use php to do this task! The sample code would get you going around!
You could view there details by firing query like
SELECT Name,Phone,Email FROM Customers
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

I got empty result with MySQL

I have tried to show the whole table data in MySQL. Rows are (User_id, first_name, last_name, and dept). There is no result when I refresh the page.
<?php
$servername = "fdb19.awardspace.net";
$username = "2598428_db";
$password = "password";
$dbname = "2598428_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="SELECT * From users";
$result = $conn->query($sql);
while($res = mysqli_fetch_array( $result )) {
echo $res['AverageSatisfactionScore'];
}
?>
Your echo is false.
You need to display a valid column name like :
echo $res['id'] or echo $res['dept'].
just try to print the total count of your result set by
echo mysqli_num_rows( $result );
it will print total number of records in the result
Also try to print whole row by
print_r($res);
insted of using
echo $res['AverageSatisfactionScore'];

Warning: mysql_select_db() expects parameter 2 to be resource,

<?php
$servername = "localhost";
$username = "root";
$password = "Rachel";
$db = "hairdressingapointments";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected Sussessfully";
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
$sql = "SELECT `ApointmentDate`, `ApointmentTime` FROM `apointments` WHERE `staff_id`=1 && `quantity`>0";
if(!mysql_query($sql)){
die('Error: ' . mysql_error());
}
echo $sql;
mysql_close();
?>
spent hours trying to figure this out and im guessing its something so simple. getting back the following error:
Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\wamp2\www\hairdressingapointments\TeresaApointments.php on line 15 which is,
mysql_select_db('Hairdressingapointments', $conn) or die(mysql_error());
You already connected to the database using
mysqli_connect(...);
So, you do not need
mysql_select_db(....);
Also change the query to this
$sql = "SELECT ApointmentDate, ApointmentTime FROM apointments WHERE staff_id=1 AND quantity>0";
If you use SQLWorkbench or SQLYog or some other tool, you can enter your SQL and make sure it is valid before adding it to your script.
Also, make sure the table name is really
apointments
and not
appointments
I got this information from php.net - mysqli_connect

Displaying MYSQL data in a HTML table AFTER a search

I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX"; 
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.