如果没有找到任何字段,请创建新字段

时间:2012-10-13 09:39:49

标签: php mysql

PHP新手在这里

我有一个名为“topics”的mysql表,我正在从表格中提取基于表单结果的页面信息(通过GET在URL中)

如果该URL不存在,我希望该表能够创建一个新条目,其中包含填写的URL中的主题名称

$ topic_name将是我将在新的topicname字段中放入的内容

到目前为止我的代码:

            $topic_name = strtolower(mysql_real_escape_string($_GET['t']));

//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");

if (mysql_numrows($topic_info)<=0) {
//insert record
$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
mysql_query($SQL);
$t_desc='NEW TOPIC : '.$topic_name;
} 
else {
//do as normal (without unnessecary loop)
$g=mysql_fetch_array($topic_info);

$t_desc = $g['desc'];               
}    
编辑:对不起,我认为我解释不好,结果来自表格的GET,所以url.com/topic?=BLAH

如果它不存在,那么它将是我想要创建的字段的名称。

该表具有自动递增“ID”(主键)

2 个答案:

答案 0 :(得分:2)

如果我理解你的错误:

$topic_name = (isset($_GET['t'])) ? strtolower(mysql_real_escape_string($_GET['t'])) : '';

//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");

if (mysql_num_rows($topic_info)<=0) {
    //insert record
    //UPDATE
    //$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
    $SQL='insert into topics (topicname, `desc`) values '.
           '("'.$topic_name.'", "NEW TOPIC DESC")';
    mysql_query($SQL);
    $t_desc='NEW TOPIC : '.$topic_name;
} else {
    //do as normal (without unnessecary loop)
    $g=mysql_fetch_array($topic_info);
    $t_desc = $g['desc'];               
} 

答案 1 :(得分:0)

尝试以下

$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");

$count = mysql_num_rows($topic_info);

if($count <= 0){
  // do insert query
}
else {
// loop through you result and display record
  while($g = mysql_fetch_array($topic_info)){
    $t_desc = $g['desc'];               
  } 
}

注意:最好使用PDO或Mysqli lib进行新开发并防止mysql注入攻击