Osa
Osa

Reputation: 1990

PHP mysql refresh select data

Some code starts with selecting data then check if row numbers are 0 to insert then continue the normal process. The problem is that the normal process is depending on the select statement which does not exist because it was stored before the insert. How can I refresh data request inside PHP without ajax or anything related to html? Here's an example to explain:

$user = $_GET['user']; // not stored user
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
$rownum = mysql_num_rows($select);
if(!$rownum){
     mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}

/* Here comes the problem */
if($row['something'] == 0){
   die("Not found !"); // THIS if returns true since it was not found at first place before inserting 
                      // i want it to refresh the $select data so it could be read as 1

}

How I solved it so far is by repeatedly using the $select and $row code below the insert statement

if(!$rownum){
     mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
   [..]

I want a simpler way to do this

Upvotes: 0

Views: 1658

Answers (1)

Waygood
Waygood

Reputation: 2683

If you know whats in the newly created record, you could just create a new array $row=array('username'->'bob', ...);

BUT if you have default values in the table, or add other things later, you going to have to do a second select.

$user=urldecode($_GET['user']);
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");

if(mysql_num_rows($result)>0)
{
    $row = mysql_fetch_array($select);
}
else
{
    mysql_query("INSERT INTO table (username, something) VALUES ('".mysql_real_escape_string($user)."', 1)");

    $result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
    if(!$result) die("SQL ERROR");
    if(mysql_num_rows($result)==0) die("MAJOR ERRORS IN SQL");

    $row = mysql_fetch_array($result);
}

I prefer to use $result as this is the result of you running the query.

Upvotes: 1

Related Questions