Check if the value exist in another table and then insert - php

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.
// Check if Codigo already exists in table2
$codigo = mysql_real_escape_string($_POST['codigo']);
$result = mysql_query("SELECT Codigo FROM table2 WHERE Codigo = '$codigo'");
if (!mysql_num_rows($result)) {
// Go ahead and insert everything in table1
$data = array(
'Nombre' => $_POST['Nombre'],
'Apellido' => $_POST['apellido'],
'Cedula' => $_POST['cedula'],
'Email' => $_POST['email'],
'Telefono' => $_POST['telefono'],
'Establecimiento' => $_POST['establecimiento'],
'Codigo' => $_POST['codigo']
);
// Make sure all the data is safe for entry into the database
foreach ($data as $key => $val) {
$data[$key] = "'" . mysql_real_escape_string($val) . "'";
}
$fields = implode(', ', array_keys($data));
$values = implode(', ', array_values($data));
$result = mysql_query("INSERT INTO table1 ($fields) VALUES ($values)");
echo 'Your data was sent';
} else {
echo 'Codigo already exists in table2';
}
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.

Simply do a SELECT query on the other table with the data you are checking for and then if mysql_num_rows() > 0 you do an insert. Something like below
$query = "SELECT * FROM otherTable WHERE infoIsSame";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$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";
}
}else{
echo "Not present in Other database";
}

One approach is to let the INSERT statement do the check for you:
INSERT INTO $tbl_name (Nombre, Apellido, Cedula, Email, Telefono, Establecimiento, Codigo)
SELECT '$nombre', '$apellido', '$cedula', '$email', '$telefono', '$establecimiento', '$codigo'
FROM table2
WHERE table2.Codigo = '$codigo'
LIMIT 1
Then check the number of rows inserted mysql_affected_rows() to determine whether a row was inserted or not. This fewer round trips to the database, for the "normative" case where you expect a row to be inserted.
NOTE: avoid using mysql_ functions and use mysqli_ or PDO instead.

Related

Find all values associated with certain value in a MySQL database

I'm creating a signup form and am onto the confirmation email part. I want to find all values associated with one other value in a database.
Ex. I get the "key" that is in the URL, then want to find all the values associated with it. In my database there are 4 columns: STR (the key), USERNAME, PASSWORD, and EMAIL. If I get STR I want to get the username, password, and email that are in the same row as the key and then insert it into another table in the same database.
verify.php:
<?php
$username = $_GET['username'];
$password = $_GET['password'];
$email = $_GET['email'];
$servername = "localhost";
$user = 'usernamelol';
$pass = 'passwordlol';
$dbname = 'vibemcform';
$str = $_GET['str'];
$conn = new mysqli($servername, $user, $pass, $dbname);
/* The variable query gets the "key" from the dont database. I want to compare that value with the other values associated with it. Ex. the variables in the same row as the key. */
$query = mysqli_query($conn, "SELECT * FROM `dont` WHERE STR='".$key."'");
/* Below is my attempt. Feel free to change whatever you want. */
$sql = "SELECT USERNAME, PASSWORD, EMAIL FROM dont";
$result = $conn->query($sql);
if (!$query) {
die('Error: ' . mysqli_error($con));
}
if (mysqli_num_rows($query) > 0) {
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sqltwo = "INSERT INTO data (USERNAME, PASSWORD, EMAIL) VALUES ($row["USERNAME"], $row["PASSWORD"], $row["EMAIL"])";
}
}
}
echo 'Successfully verified your email!'; exit;
?>
Why not simpy use the insert ... select syntax?
insert into data(username, password, email)
select username, password, email from dont where str = :key
You can run this query right ahead, and then check how many rows were affected:
If no row was affected, then it means that the select did not bring a row back: so the :key was not found in the database
If a row was affected, then the key was found and the executed row was inserted
Note that you should use parametrized queries so your code is safe from SQL injection (and more efficient as well); recommended reading How can I prevent SQL injection in PHP??

How to insert or update foreign key values using PHP

I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>

Error Querying database when insert PHP code is executed

I've been tinkering with my PHP code to insert data into a SQL table and I always get ERROR QUERYING DATABASE. The values are coming from a normal HTML form and and then when I hit submit (action=memberadd.php) I get the error message from the code below. I'm missing something but can't see what it is????
<?php
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$country = $_POST['country'];
$industry = $_POST['industry'];//only showing one - need to fix
$profile_visibility = $_POST['profile_visibility'];
$position = $_POST['position'];
$status = $_POST['status'];
$profile_link = $_POST['profile_link'];
$skills = $_POST['skills'];
//connects and sends information to the database
$dbc = mysqli_connect('localhost', 'root', 'root', 'main') or die('Error connecting to MySQL server.');
//inserts data into the member_details table main db
$query = "INSERT INTO 'member_details' (first_name, last_name, city, state, country, industry, profile_visibility, position, status, profile_link, skills)
VALUES ('$first_name', '$last_name', '$city', '$state', '$country', '$industry', '$profile_visibility', '$position', '$status', '$profile_link', '$skills')";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
mysqli_close($dbc);
echo '<h2>Here are your details.</h2>';
echo '<h3>First Name: '.$first_name.'<br />';
echo '<h3>Last Name: '.$last_name.'<br />';
echo 'City: '.$city.'<br />';
echo 'State: '.$state.'<br />';
echo 'Country: '.$country.'<br />';
echo 'Industry: '.$industry.'<br />';//only showing one - need to fix
echo 'Profile: '.$profile_visibility.'<br />';
echo 'Position: '.$position.'<br />';
echo 'Status: '.$status.'<br />';
echo 'Link: '.$profile_link.'<br />';
echo 'Skills: '.$skills.'<br /></h3>';
?>
The Problem
As #Fred -ii- has noted the problem is with the quotes being around the table name in your INSERT statement.
$query = "INSERT INTO 'member_details' (first_name, ...
^ ^
The solution
If you wish to 'quote' table or column names, you should use backticks which you can read more about on the MySQL documentation page.
$query = "INSERT INTO `member_details` (first_name, ...
Detecting errors
To check a MySQLi database request for errors there are a few methods that can be used to get error information. Probably the most useful is mysqli_error() which will give you an error string.
$result = mysqli_query($dbc, $query);
if(!$result)
{
printf("Errormessage: %s\n", mysqli_error($dbc));
}
As #Fred -ii- also mentioned you should use error reporting correctly when developing new code. Ideally you should configure this in your php.ini, but it can also easily be done by adding the following to the top of your page(s).
error_reporting(E_ALL);
ini_set('display_errors', 1);
Finally, you're wide open to SQL Injection Attacks. You should look into using prepared statements with MySQLi to help prevent this.
You can use mysql query like...
$query = "INSERT INTO `member_details` SET first_name = '".$first_name."', last_name = '".$last_name."', city = '".$city."', state = '".$state."', country = '".$country."', industry = '".$industry."', profile_visibility = '".$profile_visibility."', position = '".$position."', status = '".$status."', profile_link = '".$profile_link."', skills = '".$skills."'";

PHP Database only inputs the last value

I have almost no experience with PHP and right now I'm stuck at the total beginning, which is really frustrating. I have a code, which seems to work. From my app I can input values and put them in my PHP database. Thing is that he only inputs the very last value from my PHP code. So the app aside: If I only use the PHP code to input something in my database he always only takes the last value. Here is my code:
<?php
$DB_HostName = "localhost";
$DB_Name = "xxx";
$DB_User = "xxx";
$DB_Pass = "xxx";
$DB_Table = "contacts";
if (isset ($_GET["name"]))
$name = $_GET["name"];
else
$name = "Blade";
if (isset ($_GET["lastname"]))
$lastname = $_GET["lastname"];
else
$lastname = "Xcoder";
if (isset ($_GET["number"]))
$number = $_GET["number"];
else
$number = "111";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql = "insert into $DB_Table (Lastname) values('$lastname');";
$sql = "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
To clarify: If I only have the firstname value, he inputs it in the right place (firstname). If I have a firstname and lastname value, he only inputs the lastname value, but not the firstname value (still at the right place lastname). And the same for number. If I have a firstname, lastname and a number, he only puts the number in the right place but not the other values. In addition I can only do it once. If I want to enter another contact he always says (Duplicate entry 'myentry' for key 'PRIMARY').
You overwrite your query, 2 ways to solve. Either 3 different variables, or 1 variable with 3 queries in it. I would prefer the 2nd option
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Or if it can be 1 row in the table, as it is the same table anyways:
$sql = "insert into $DB_Table (Firtname,Lastname,Number) values('$name','$lastname','$number');";
$res = mysql_query($sql,$con) or die(mysql_error());
Because you are overwriting $sql on the next 2 lines, so the final sql line is what is inserted.
Your sql is wrong if you want them all in the same row.
$sql = "insert into $DB_Table (Firtname,lastname,number) values('$name','$lastname','$number');";
You are overwriting your $sql statements. You have to execute them. By doing:
$sql = "Insert INTO..."
you merely set a a variable. You need to ru each query using mysql_query().
I'm also guessing that you want to do this:
$sql = "INSERT INTO $DB_TABLE (Firstname, Lastname, Number) VALUES ('$name', '$lastname', '$number')
Finally, it is crucial that you sanitise your inputs:
$name = mysql_real_escape_string($_GET["name"]);
Thanks to this you avoid an SQL Injection attack.
You are overwriting $sql string each time.
Perhaps you meant to use the .= to append all three queries together. What is the structure for database tables?
$sql = "insert into $DB_Table (Firtname) values('$name');";
$sql .= "insert into $DB_Table (Lastname) values('$lastname');";
$sql .= "insert into $DB_Table (Number) values('$number');";
That is because you use the same variable name ($sql) for all 3 queries. Use $sql1, $sql2 and $sql3 instead. Also, call mysql_query for each one (but only if you've set it).
Like this:
$sql1 = "insert into $DB_Table (Firtname) values('$name');";
$sql2 = "insert into $DB_Table (Lastname) values('$lastname');";
$sql3 = "insert into $DB_Table (Number) values('$number');";
if (isset ($sql1))
{
$res1 = mysql_query($sql1,$con) or die(mysql_error());
}
if (isset ($sql2))
{
$res2 = mysql_query($sql2,$con) or die(mysql_error());
}
if (isset ($sql3))
{
$res3 = mysql_query($sql3,$con) or die(mysql_error());
}

php mysql query not executing correctly

I have a weird problem with my sql script.
I have a string
$query = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message)
VALUES ('93361357', '2162', '27761144734', 'Hoekom');";
But when I execute that string it inserts it to the table but eventid stays 0, if I run that exact command in cmd it works perfectly?
Any ideas why this is not inserting all the values?
Edit Full code
<?php session_start();
$link = mysql_connect("localhost", "username", "password"); //removed u and p for posting
if (!$link)
die("Couldn't connect to MySQL");
mysql_select_db("db", $link) //removed db name for posting
or die ("Couldn't open smss:" . mysql_error());
$id = $_SESSION['id'];
$message = $_REQUEST['promo_message'];
$timeToSend = $_REQUEST['timeToSend'];
$dateToSend = $_REQUEST['dateToSend'];
if(isset($_REQUEST['input_cell']))
{
$receiver = $_REQUEST['input_cell'];
if($receiver != '')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
mysql_query($query1);
echo mysql_error();
}
}
if(isset($_REQUEST['single_cell']))
{
$receiver = $_REQUEST['single_cell'];
if($receiver != 'none')
{
$response_string = sendSMSPortalSchedule($message, $receiver, $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$query2 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query2);
echo mysql_error();
}
}
if(isset($_REQUEST['sento_group']))
{
$array = $_REQUEST['sento_group'];
foreach($array as $receiver)
{
if($receiver != 'none')
{
$query = 'SELECT cell_number FROM cell_groups WHERE group_id ="'.$receiver.'"';
$result2 = mysql_query($query) or die('Fail');
while($row=mysql_fetch_array($result2))
{
$response_string = sendSMSPortalSchedule($message, $row['cell_number'], $sender_id, $dateToSend, $timeToSend);
$response_string = str_replace ( "True" , "", $response_string );
$to = $row['cell_number'];
$query3 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$to', '$message');";
//This does not work right, all gets added perfectly yet eventid stays 0 enven while all the others get the right values
mysql_query($query3);
echo mysql_error();
}
}
}
}
}
This is the table
id = INT
eventid = BIGINT(20)
bus_id = INT
cell_num = VARCHAR
sms_message = VARCHAR
The SQL command itself is correct. The problem must be elsewhere.
Firstly, are you sure that the values of your parameters are correct? Try outputting the query after variable interpolation to see if it is correct:
$query1 = "INSERT into sms_replyid (eventid, bus_id, cell_num, sms_message) VALUES ('$response_string', '$id', '$receiver', '$message')";
echo $query1;
Seondly I notice that in you have INSERTs in multiple places. Make sure all of them work as expected. Remember that the one you think is executing may be different from the one that is actually executing.
I found the problem, the service I was using got changed to return XML where it usually just returned an integer, this caused me to try and insert XML into my BIGINT field, which is not possible. So in the end the problem was caused by an updated service that didn't notify clients about changes.

Categories