Reputation: 1
This is my php code. How to check if this 3 parameters (user,agwera,vis) exist in MySQL with PHP? And if already exist don't add a second time. + want echo "Already in Exists<br/>";
<?
sleep(10);
define ('DBHOST', 'yyy');
define ('DBNAME', 'xxxx');
define ('DBUSER', 'xxxx');
define ('DBPASS', 'xxxxx');
mysql_pconnect(DBHOST, DBUSER, DBPASS) or die('DB');
mysql_select_db(DBNAME) or die ('USER');
mysql_query('SET NAMES utf8');
header('Content-Type: text/html; charset=utf-8');
error_reporting (0);
$act = isset($_GET['act']) ? $_GET['act'] : '';
switch($act)
{
case 'send':
$destination = $_POST['adress'];
$signature = $_POST['text'];
$text = "$signature ";
if (empty($_POST["text"]) or strlen($_POST["text"])==0){
@header("location:error5.php");
break;
}
$str = $_POST['text'];
if (strlen($str)>160){
@header("location:error4.php");
break;
}
if (!preg_match('/^[0-9]{9}$/',$destination))
{
@header("location:error1.php");
break;
}
$str2 = $_POST['sender'];
if (strlen($str2)>11){
@header("location:error2.php");
break;
}
if (empty($_POST["sender"]) or strlen($_POST["sender"])==0){
@header("location:error3.php");
break;
}
else
{
$password = 'zzzzzz';
$destination = $_POST['adress'];
$nomeri = "995$destination";
$nomeri2 = $_POST['sender'];
$source = $nomeri2;
$signature = $_POST['text'];
$text = "$signature ";
$content =
'key='.rawurlencode($password).
'&destination='.rawurlencode($nomeri).
'&sender='.rawurlencode($source).
'&content='.rawurlencode($text);
$a = file_get_contents('http://example.com/api/send.aspx?'.$content);
@header("location:ok.php");
mysql_query("INSERT `gagzavnili` SET
`user` = '".$source."',
`agwera` = '".$text."',
`vis` = '".$destination."',
`time_upload` = '".time()."',
`time` = '".time()."'") or die(mysql_error());
$file_id = mysql_insert_id();
}
}
?>
Upvotes: 0
Views: 2342
Reputation: 13
$data = array('user', 'agwera', 'vis');
foreach( $data as $val ) {
$res = mysql_query("SELECT * FROM `table_name` WHERE `column_name` = '$val'");
$count = mysql_num_rows($res);
if( $count > 0 ) {
echo "<script>alert('Already Exists')</script>";
} else {
//insert query for $val...
}
}
Upvotes: 1
Reputation: 3251
First, it's June 2014, you shouldn't be using the mysql* lib anymore. Switch to mysqli.
Second, there is no truly elegant way to do this without making two queries.
Run a query to select the row with the parameters you specified. Something along the lines of
SELECT COUNT(<some field>) FROM <table name> WHERE field1 = 'value' AND...
If count comes back greater than zero, the entry exists. This doesn't just go for PHP, but for any time you want to see if data exists in a database (in your case MySQL).
Upvotes: 0