让两个脚本一起工作

时间:2012-02-13 19:36:56

标签: php mysql scripting

我正在尝试使用以下脚本,以便第一个脚本的结果决定第二个脚本的输出。

<?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);

$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($result)) 

if ( $row['pool'] % 2 )
{ 
echo "<h4>Result 1</h4>";
echo "<br />";
}
else
{ 
echo "<h4>Result 2</h4>";
echo "<br />";
}
?>


<?php

$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbnamesameasother', $db);


$query2 = "SELECT * FROM comments";
$result2 = mysql_query($query2);

while ($row2 = mysql_fetch_assoc($result2))

if ( $row2['commentid'] % 2 ==0 )
{ 
echo $row2['name'];
echo "<br />";
}
else
{
echo $row2['name'];
}
?>

所以基本上如果第一个脚本选择结果1我只想回显与该结果相关联的名称。这些名字与名称相关联,其中奇数名义将是结果2而偶数名义将是结果1.如果不使用联合声明,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

建议你创建一个函数,然后调用它。这样的东西:

<?php
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);

$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($result)) 

if ( $row['pool'] % 2 )
{ 
echo "<h4>Result 1</h4>";
$names = get_names(1);
  foreach ($names as $name) {
   echo $name . "<br/>";
  }
}
else
{ 
echo "<h4>Result 2</h4>";
$names = get_names(0);
  foreach ($names as $name) {
   echo $name . "<br/>";
  }
}

Function get_names($pool_result) 
{
  $name_array = array();
  $db = mysql_connect('localhost','username','pass') or die("Database error");
  mysql_select_db('dbnamesameasother', $db);

  $query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result"; 
  $result = mysql_query($query);

  while ($row = mysql_fetch_array($result))
  {
    array_push($name_array , $row['name']);
  }
  return $name_array;
}
?>

}