如果唯一行中的空字段更新或插入?

时间:2013-09-27 09:29:50

标签: php mysql

必须有一种更简单的查询表的方法,如果该行有DATA然后UPDATE,ELSE INSERT INTO表。他们分别处理UPDATE或INSERT,但他们一起继续插入另一行。我只想为每个唯一ID保留一行。我对IF声明很恐怖。

$result = mysql_query($query);
$row= mysql_numrows($result);


if( isset($row) AND $row > 0 )    //probably could use isset here or empty
{
    $sql= " Update afillInfo  
            JOIN actorsInfo ON actorsInfo.id = afillInfo.id_actor
            SET afillChoice = '$afillChoice',
                agency = '$agency',
                agentPhone = '$agentPhone'
                WHERE email = '$_SESSION[email]'";

    if (!mysqli_query($sql))
    {
        die('Error: ' . mysqli_error($sql));
    }
}
else
{
    $sql = "INSERT INTO afillInfo 
            (agency, agentPhone, afillChoice, id_actor)
            VALUES
            ('$_POST[agency]','$_POST[agentPhone]','$_POST[afillChoice]'),
            ( select id FROM actorsInfo WHERE email = '$_SESSION[email]')
            )";

    if (!mysqli_query($sql))
    {
        die('Error: ' . mysqli_error($sql));
    }
}

3 个答案:

答案 0 :(得分:0)

$query = "select count(*) as count .... rest of the query"
$result = mysql_query($query);
$data = mysql_fetch_assoc($result);



if($data['count'] > 0)
{   
    $sql= "Update afillInfo  join actorsInfo 
    ON   actorsInfo.id = afillInfo.id_actor
    SET afillChoice = '$afillChoice',
    agency = '$agency',
    agentPhone = '$agentPhone'
    WHERE email = '$_SESSION[email]'";

    if (!mysqli_query($sql))
    {
    die('Error: ' . mysqli_error($sql));
    }
}
else{

    $sql="INSERT INTO afillInfo (agency, agentPhone, afillChoice, id_actor)
    VALUES
    ('$_POST[agency]','$_POST[agentPhone]','$_POST[afillChoice]', 
    ( select id FROM actorsInfo WHERE email = '$_SESSION[email]'))";

    if (!mysqli_query($sql))
    {
    die('Error: ' . mysqli_error($sql));
    }
}

答案 1 :(得分:0)

插入afillInfo(agency,agentPhone,afillChoice,id_actor)VALUES     ( '$ _ POST [代理]', '$ _ POST [中介电话]', '$ _ POST [afillChoice]',     (选择id FROM actorsInfo WHERE email ='$ _SESSION [email]'))

on duplicate key update agency = values(agency),agentPhone = values(agentPhone),afillChoice = values(afillChoice),id_actor = values(id_actor)

答案 2 :(得分:0)

尝试使用mysql_num_rows功能时出现问题,并检查$num_rows将返回给您的内容。

$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);

$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);

echo "$num_rows Rows\n";