Jump to content

Yet another syntax issue.


dlyles

Recommended Posts

The below coding is supposed to look through the db and if the record doesn't exist, insert the record into the db.

[code]
$groupname=mysql_real_escape_string($_POST['groupname']);

$sqll="select * from groups where GroupName = '". $groupname . "'";
$nresult=mysql_query($sqll);
$nrow=$row['groupname'];
$count=mysql_num_rows($nresult);
if($count==1){

$sql = "insert into groups (GroupName) VALUES ('" . $groupname . "')";
$result = mysql_query($sql) or die("Error 2: query: $sql<br>" . mysql_error());
echo $sql;
echo "1 record added";

}
else
{
echo "nah";
}

?>

[/code]
I've put data in the field that I know is already in there and some I know aren't and I get the same result.  It's assuming the value is there and not updating the db.
Link to comment
https://forums.phpfreaks.com/topic/28985-yet-another-syntax-issue/
Share on other sites

[quote]It's assuming the value is there and not updating the db.[/quote]

The logic in your code is bacwards. Basically you are checking the database to see if a particular groupname already exists. If it DOES exist then you add it to the database again. Shouldn't that add the group name if it does NOT already exist? Also, unless you have set the groupname field int he database to be a unique column you shouldn't use if($count==1){, instead use if($count>0){

Also this line [code]$nrow=$row['groupname'];[/code] has no purpose and wouldn't equal anything anyway since you did not retrieve the data from the query using something liek mysql_fetch_assoc().

If there is no record there, then $count would be zero, not 1, so the "if" statement should be
[code]<?php
if($count == 0){
?>[/code]

Also, you have this statement
[code]<?php
$nrow=$row['groupname'];
?>[/code]
which won't give you anything meaningful, since you haven't fetched any rows at that time.

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.