简体   繁体   English

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

[英]Check Data in MySQL row before Insert using php 5.3

I want to check that URL is already available in table or not before insert using php 5.3. 我想在使用php 5.3插入之前检查URL在表中是否可用。

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

if i am add abc it give me value stored in col 2[surl] xyz. 如果我添加abc,则会为我提供存储在col 2 [surl] xyz中的值。
and if not add this in database. 如果没有,则将其添加到数据库中。

<?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);
}
?>

check your both db field type id text or varchar i think tmp is a string valus so you need to match in quote then try:- 检查您的两个数据库字段类型ID文本或varchar我认为tmp是一个字符串值,因此您需要匹配引号,然后尝试:-

 $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);

Select your database before continuing with your query and as @Rakesh said if the db type is text or varchar wrap your values with quotation marks. 在继续查询之前,请选择数据库,并按照@Rakesh的指示,如果数据库类型是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

In Mysql,you should quote a string with '' or "" like this: 在Mysql中,您应使用以下字符引用带有“或”的字符串:

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

if tmp is a php variable, you code should like that: 如果tmp是一个php变量,则您应该编写如下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM