0

I have a problem in if else condition. Sorry i am a beginner so please help me. My code is below.

$sql1=mysql_query("select * from dbms_master_data where id='".$_GET['eid']."'");

$rst1=mysql_fetch_array($sql1);
$new_user='Contact; '.$rst1['user_type'];
$sqls=mysql_query("update dbms_master_data set user_type='".$new_user."', cid='".$_GET['vid']."' where id='".$_GET['eid']."' and cid IS NULL");
if($sqls)
{
    ?>
    <script>
    alert("New contact added!");
    window.location='access1.php?vid=1';
    </script>
    <?php
}
else
{
    ?>
    <script>
    alert("This contact is already assigned to another user!");
    window.location='access1.php?vid=2';
    </script>
    <?php
}

I am getting 'New contact added' message even my condition fails. Could you please tell me why?

Sougata Bose
  • 31,517
  • 8
  • 49
  • 87

4 Answers4

0

Your condition is wrong

if($sqls) it will always return true, since mysql_query() response returns the resource id.

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
0

Use mysql_num_rows(). It is use to check number of affected row

$sqls=mysql_query("update dbms_master_data set user_type='".$new_user."', cid='".$_GET['vid']."' where id='".$_GET['eid']."' and cid IS NULL");

$row=mysql_num_rows($sqls);
if($row>0)
{
    ?>
    <script>
    alert("New contact added!");
    window.location='access1.php?vid=1';
    </script>
    <?php
}
else
{
    ?>
    <script>
    alert("This contact is already assigned to another user!");
    window.location='access1.php?vid=2';
    </script>
    <?php
}
Saty
  • 22,443
  • 7
  • 33
  • 51
0

As said above use if(mysql_num_rows($sqls) > 0) { but consider using PDO, PHP no longer recommends mysql_query so worth your while getting to grips with PDO if you're learning.

Also make sure you escape anything going into your database, people can easily inject things if you don't. Example (in the context of your queries):

$sql1=mysql_query("select * from dbms_master_data where id=".(int)$_GET['eid']);

$rst1=mysql_fetch_array($sql1);
$new_user='Contact; '.$rst1['user_type'];
$sqls=mysql_query("update dbms_master_data set user_type='".mysql_real_escape_string($new_user)."', cid=".(int)$_GET['vid']." where id=".(int)$_GET['eid']." and cid IS NULL");
0

It is necessary to check if it is updated or not. So please use

mysql_affected_rows()
Ronak Patel
  • 3,324
  • 4
  • 21
  • 31