开发者

How can I query the mysql database for a variable, if exists create another variable, if not insert?

say I have a variable

$id = mt_rand();

how can I query the mysql database to see if the variable exists in the开发者_如何转开发 row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?

Thanks you guys.


$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
    mysql_select_db('<schemata>', $con);
    $found = false;
    while (!$found) {
        $idIamSearching = mt_rand();
        $query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
        $result = mysql_fetch_row($query);
        if ($result[0] > 0) {
            mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
            $found = true;
        }
    }
    mysql_close($con);
}

Your description is hard to understand, so, this is something that could give you pointers...


'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'

make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters

then fetch the row and check if count is 1 or greater than 0

if one, then it exists and try again (in a loop)

although, auto increment on the id field would allow you to avoid this step


$bExists = 0;
while(!$bExists){
    // Randomly generate id variable
    $result = mysql_query("SELECT * FROM table WHERE id=$id");
    if($result){
        if(mysql_num_rows($result) > 0){
        $bExists = 1;
    } else {
        // Insert into database
        $bExists = 1;
    }
}

1 Randomly generate id variable 2 Query database for it 2.1 Result? exit 2.2 No result? Insert

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜