简体   繁体   中英

in_array function returning true always

I'm constructing a webpage to submit camera bookings to a MYSQL database. This webpage has a html frontend that forwards it to the following PHP page, which then submits that information to the MYSQL Currently the client wishes for there to be no way of making duplicate bookings of the Cameras. To fulfill this, I have constructed the following PHP page, which checks if the chosen camera in the html frontend ($_POST[camera]) is the same as anything in the $result_array array. The code is as follows:

<?php
$con = mysql_connect("****","*****","*******");

if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("****", $con);
$query = "SELECT Camera FROM T_Bookings";
$result = mysql_query($query) or die ("no query");
$result_array = array();

while($row = mysql_fetch_array($result)) {
  $result_array[] = $row;
}

$fixed_array = array_keys($result_array);

if (in_array($_POST[camera],$result_array)){
  $x = 1;
  $y = 2;
}

if($x + $y == 3){
  echo "Camera already booked!";
}
else {
  mysql_query("INSERT INTO T_Bookings (F_Name, L_Name, Camera, Bag, Cable, Tripod, MemoryCard, Date, Authorised) 
VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[camera]','$_POST[bag]','$_POST[cable]','$_POST[tripod]','$_POST[memory]','$_POST[date]',)");

  echo "1 record added";

  if (!mysql_query($sql,$con)) {
    die('Error: ' . mysql_error());
  }
}

mysql_close($con);
?> 

However, it is consistently placing a booking even if these conditions aren't met. Why is this the case? Thanks, Dayne.

mysql_fetch_array($result) returns an array like

array('Camera' => 'Whatever')

So change the line below to read

$result_array[] = $row['Camera'];

There's a fundamental flaw in your logic. You have a requirement for a unique value and the current implementation does not provide any such guarantee (learn about ACID on Wikipedia: http://en.m.wikipedia.org/wiki/ACID ).

You're in luck though. MySQL happens to provide just what you need with little effort. Create a unique index on the Camera column (http://dev.mysql.com/doc/refman/5.5/en/create-index.html). Then don't check for a previous entry with the same name. Simply try to do an insert. MySQL will return an error which is easily handled and your code just became simpler, easier to read and manage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM