Jump to content

PHP If statement (mysql query help)


Cosizzle

Recommended Posts

Hello,

 

Im still a little new to strining a query then calling it through PHP. Im wanting to create a small error check against a database which I have working.

 

$query = "SELECT COUNT(*) AS cnt FROM vin_t , dcode_t WHERE dcode_t.dcode_id = vin_t.vin_id AND vin_t.vin = '$vin' AND dcode_t.dcode = '$dc'";

$result = mysql_query($query) or trigger_error("Query: $query <strong>mysqlError:" . mysql_error());

 

I need to create an If statement that will check to see if COUNT... or cnt is set to 1. If it is, pass it - if not give error.

 

From my understanding I have to run

mysql_fetch_array

but yea... kinda confused. Thanks for the help!

Link to comment
https://forums.phpfreaks.com/topic/98847-php-if-statement-mysql-query-help/
Share on other sites

<?php

$query = "SELECT COUNT(*) AS cnt FROM vin_t , dcode_t WHERE dcode_t.dcode_id = vin_t.vin_id AND vin_t.vin = '$vin' AND dcode_t.dcode = '$dc'";

if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    $row = mysql_fetch_assoc($result);
    if ($row['cnt'] = 1) {
      // do something
    } else {
      // do something else
    }
  }
}

Better still would be to get it done in your query.

 

<?php

$query = "SELECT COUNT(*) AS cnt FROM vin_t , dcode_t WHERE cnt =1 AND dcode_t.dcode_id = vin_t.vin_id AND vin_t.vin = '$vin' AND dcode_t.dcode = '$dc'";

if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    // do something
  } else {
    // do something else
  }
}

?>

Thank you, I ended up using the first for the sake of confusion... made more sense to me - I still have a lot to learn!!

 

For future refrences the first had a small error.

($row['cnt'] = 1) should be ($row['cnt'] == 1)

Nothing major.

 

Thanks again

 

<?php

$query = "SELECT COUNT(*) AS cnt FROM vin_t , dcode_t WHERE dcode_t.dcode_id = vin_t.vin_id AND vin_t.vin = '$vin' AND dcode_t.dcode = '$dc'";

if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    $row = mysql_fetch_assoc($result);
    if ($row['cnt'] == 1) {
      // do something
    } else {
      // do something else
    }
  }
}

 

 

 

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.