I’m working on a form in PHP that inserts data to MySQL, but before the data is inserted there is a field that must be checked in another table before inserting. If this value exist in the other table, then the data is inserted in the main table, if not, then data is not inserted.
Here is my code to insert the data:
$host = "localhost";
$username = "root";
$password = "";
$db_name = "forms";
$tbl_name = "table1";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$cedula = $_POST['cedula'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$establecimiento = $_POST['establecimiento'];
$codigo = $_POST['codigo'];
$sql = " INSERT INTO $tbl_name(Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)VALUES('$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo')";
$result = mysql_query($sql);
if ($result) {
echo "Your data was sent";
} else {
echo "You inserted a wrong code";
}
?>
<?php
// close connection
mysql_close();
?>
So, what I need is to check the value $codigo in table2, if exists, then insert $codigo in table1 with the other values. This is where I’m stuck.
All you really need to do is this.
But please note there are many ways of doing this that are far better and more efficient. For one, I would recommend you use PHP’s mysqli functions rather than the deprecated mysql ones (http://www.php.net/manual/en/book.mysqli.php)
More importantly, you don’t look like you’re protecting your queries against SQL injection at all. Please read up on this, but it’s usually just a need for real_escape_string() on any value you are inserting into a SQL query.