1

Originally, this simple array and a foreach statement works perfect, but I need to change from a php array to getting the information out of the database:

$serversArray = array(
    "domainname1.com",
    "domainname2.com:port",
    "domainname3.org",
    "000.000.000.000:port");

foreach($serversArray as $server)

.

ID    IP                Port
1     domainname1.com   
2     domainname2.com   12345
3     domainname3.org   
4     000.000.000.000   54321

What I need to figure out is how to get the IP and Port columns formatted into ip:port (with the colon in between), and then make the foreach statement recognize each one so it can process it with some other script, just like how it works already with the array. (I have also tried using sprintf in the foreach, but that broke the page.)

3
  • Please show the code you are using to retrieve information from the database, as well as the rest of your foreach loop. Commented Dec 27, 2012 at 0:34
  • 1
    please see this SO question for a quick rundown on how to proceed with a sql query. Commented Dec 27, 2012 at 0:41
  • @DreamPhreak So what error are you getting that is preventing page load? Why would you not share the code you have so any problems can be identified? Commented Dec 27, 2012 at 0:50

2 Answers 2

2

Here's how you get the query to come back in the right format:

SELECT IF(`PORT` IS NULL, `IP`, CONCAT(`IP`,":",`PORT`)) as `Formatted IP`
FROM YOUR_TABLE;
Sign up to request clarification or add additional context in comments.

Comments

1

Do you want build the $serversArray from a DB query?

$serversArray = array();
$sql     = "SELECT ip, port FROM my_table";
$result = mysql_query($sql);
while ($row  = mysql_fetch_array($result))
{
    // if have port include it after : otherwise just include ip
    $serversArray[] = $row['port'] ? "{$row['ip']}:{$row['port']}" : $row['ip'];
}


Old fashion sql queries are just to show the procedure to build the array. At the present time we should use MySQL Functions (PDO_MYSQL)

2 Comments

That is PERFECT, the foreach statement and the rest of the page and working as they should, without the manual array. I have never seen anything like that, but thanks!
@dreamphreak Happy for you, go for it... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.