0

How do you get all the data from a column in an SQL table and check it against data you get from a form? Here's what I have so far:

<?php
 $con=mysqli_connect("www.tqbtest.comlu.com","a5349216","Password","a5349216_test");
 if (mysqli_connect_errno())
   {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
   }

 //How do I check the data from the form to make sure there is no username/email already used?

 $sql="INSERT INTO Profiles (firstName, lastName, username, email, password, region, profileGroup, verified)
 VALUES
 ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

 if (!mysqli_query($con,$sql))
   {
   die('Error: ' . mysqli_error($con));
   }
 echo "1 record added";

 mysqli_close($con);


?>
Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
TheQuantumBros
  • 308
  • 2
  • 4
  • 16
  • possible duplicate of [MySQL: Insert record if not exists in table](http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table) – GolezTrol Jun 30 '13 at 00:07
  • Above thread explains problem and solution for MySQL, although it's not specific to PHP. I would choose both solutions, actually: make the field unique to prevent double registrations, but also make the insert smarter so it inserts nothing if a record already exists. You can then get the number of [affected rows](http://php.net/manual/en/mysqli.affected-rows.php) to see if a record was inserted. If not, you can assume that it already existed. – GolezTrol Jun 30 '13 at 00:10
  • I know it sounds like a broken record around here but please read up on SQL injection http://php.net/manual/en/security.database.sql-injection.php, and also consider switching from mysqli to PDO http://php.net/manual/en/book.pdo.php – Kris Jun 30 '13 at 00:28

2 Answers2

0

You have a couple options:

  • you can add a unique index to any field you wish to be unique. They will cause any inserts which violate your uniqueness constraints to fail, which you can then capture and feed back to your application.
  • you can try doing a select against your table for the fields you wish to be unique and see if you get a result back. If you do, you can throw an error back to your user.
dethtron5000
  • 8,763
  • 1
  • 27
  • 31
0

I think this is what you need:

$DBsql = mysql_query("select col1, col2 from table_name where some_id = $some_id");
$sql = mysql_fetch_array($DBsql);

if(($_POST['field1'] == $sql['col1']) && ($_POST['field2'] == $sql['col2'])) {
    echo 'The fields are valid';
} else {
    echo 'One or more fields are not valid';
}
vio
  • 29
  • 2