使用php 5.3在Insert之前检查MySQL行中的数据

时间:2013-08-19 05:05:19

标签: php mysql php-5.3

我想在使用php 5.3插入之前检查表中是否已有URL。

+-------------+-----------+
+    durl    +    surl  +
+-------------+-----------+
+   abc       +    xyz    +
+   mno       +    pqr    +
+   efg       +    jkl    +
+-------------+-----------+

如果我添加abc,它会给我存储在col 2 [surl] xyz中的值 如果不在数据库中添加它。

<?php
$dbhost = '****';
$dbuser = '****';
$dbpass = '****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}
$query="select * from new where durl = tmp";
$result = mysql_query($query);
if (mysql_num_rows($result)>0) {
    // return value of col 2
} 
else { 
$sql = 'INSERT INTO new '.
        '(durl,surl) '.
        'VALUES ( "tmp", "XYZ")';
mysql_select_db('a4806808_my');
$retval = mysql_query( $sql, $conn );
mysql_close($conn);
}
?>

3 个答案:

答案 0 :(得分:0)

检查你的db字段类型id文本或varchar我认为 tmp 是一个字符串valus所以你需要在引用中匹配然后 尝试: -

 $query="select * from new where durl = 'tmp'";
    $result = mysql_query($query);
    if (mysql_num_rows($result)>0) {
        // return value of col 2
    } 
    else { 
    $sql = 'INSERT INTO new 
            (durl,surl)
            VALUES ( "tmp", "XYZ")';
    mysql_select_db('a4806808_my');
    $retval = mysql_query( $sql, $conn );
    mysql_close($conn);

答案 1 :(得分:0)

在继续查询之前选择你的数据库,并且@Rakesh说如果db类型是text或varchar用引号包装你的值。

<强> EG:

$dbhost = '****';
$dbuser = '****';
$dbpass = '****';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db('a4806808_my') or die("couldn't select the database"); //select your database before continuing

$query="select * from new where durl = 'tmp'"; //use quotation marks around 'tmp' as rakesh said.
$result = mysql_query($query);
if (mysql_num_rows($result)>0) {
   // return value of col 2
} else { 
   $sql = 'INSERT INTO new '.
        '(durl,surl) '.
        'VALUES ( "tmp", "XYZ")';
   $retval = mysql_query( $sql, $conn );
}

mysql_close($conn); //close your connection after everything is done

答案 2 :(得分:0)

在Mysql中,你应该用&#39;&#39;引用一个字符串。或&#34;&#34;像这样:

$query="select * from new where durl = 'tmp'";

如果tmp是一个php变量,你的代码应该是这样的:

$query="select * from new where durl = '$tmp'";