这是我的PHP代码。如何用PHP验证MySQL中是否存在这3个参数(user,agwera,vis)?如果已经存在则不要再添加第二次。 +想要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();
}
}
?>
答案 0 :(得分:1)
$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...
}
}
答案 1 :(得分:0)
首先,它是2014年6月,你不应该再使用mysql * lib了。切换到mysqli。
其次,如果不进行两次查询,就没有真正优雅的方法。
运行查询以选择包含您指定参数的行。
的内容SELECT COUNT(<some field>) FROM <table name> WHERE field1 = 'value' AND...
如果count返回大于零,则表示该条目存在。这不仅适用于PHP,而且您可以随时查看数据库中是否存在数据(在您的情况下是MySQL)。