Jump to content

Variables to an array and looping


mattyvx

Recommended Posts

Hello,

 

I'm taking values for various cities/areas my members live in. One member can be placed in many cities and on registering they are required to input one city but are allowed to enter a maximum of 6 cities.

 

So, from my posted form I have;

 

//member ID (numeric)
$MemID;

$City=$_Post['City'];
$City2=$_Post['City2'];
$City3=$_Post['City3'];
$City4=$_Post['City4'];
$City5=$_Post['City5'];
$City6=$_Post['City6'];

 

Where $City must be set, but any of the other $City'x' may or may not be empty.

 

There are two tables, 1) Cities (CityID,City)        2) Mem-Cities (MemID,CityID).

 

I have some SQL statements which check if the city exists and if it doesn't inserts it. Then adds the $MemID to that $CityID.

 

The way im doing this now is not very efficient like this;

 

if(!empty($City))
{
$sql="SELECT COUNT(City) AS Count FROM Cities WHERE City='$City'";
$query=mysql_query($sql);
$row=mysql_fetch_array($query);
  if($row['Count'] == 0)
  {
  $insert="INSERT INTO Cities
  (City) VALUES ('$City')";
  mysql_query($insert) OR die('<h1>There was an error adding into Cities</h1>' .mysql_error());
//inserting additional City
  }
  $insert="INSERT INTO Mem-Cities
  (MemID,CityID) SELECT '$MemID',CityID FROM Cities WHERE City='$City' LIMIT 1";
  mysql_query($insert) OR die('<h1>There was an adding additional City Cities to members</h1>' .mysql_error());
//inserting additional city into Cities to Members
}

 

And repeating the code above for each city.

 

How can I loop through each city and optimise this code?

 

Steps

1) if $City'x' is not empty and doesn't exist in DB insert it

2) add the $MemID to that CityID

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/223890-variables-to-an-array-and-looping/
Share on other sites

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.