PHP mySQL resource query?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ziycon
    Contributor
    • Sep 2008
    • 384

    PHP mySQL resource query?

    I have this first piece of code which works fine but I'm trying to break it up into two parts like in the second code snippet below.
    Code:
    $tables = mysql_query("SHOW tables;");
    while($row = mysql_fetch_array($tables)) {
    	$tableNames .= "<a href=\"".$_SERVER['PHP_SELF'].">".$row[0]."</a><br/>\n";
    	$tableCount++;
    }
    So it passes the sql query to the function and the function runs the query and should return the resource and store it in $tables variable and then the while loop should run through the $tables variable the same as in the first code snippet but it doesn't seem too work, its only outputting the first table name twice and there is over 100 tables!?
    Code:
    $tables = $this->dbQuery("SHOW tables;");
    while($tables) {
    	$tableNames .= "<a href=\"".$_SERVER['PHP_SELF'].">".$table."</a><br/>\n";
    	$tableCount++;
    }
    /******************************************/
    function dbQuery($queryIn) {
    	$resource;
    	
    	switch ($_SESSION['dbtype']) {
    		case 0:
    			$sql = mysql_query($queryIn);
    			$resource = mysql_fetch_array($sql);
    			break;
    	}
    
    	return $resource;
    }
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    personally, I’d use foreach() like
    Code:
    // use CSS to make it a block element!
    $format = '<a href="'.$_SERVER['SCRIPT_NAME'].">%s</a>" . PHP_EOL;
    $tables = $this->dbQuery("SHOW tables;");
    foreach ($tables as $table) 
    {
        $tableNames .= sprintf($format, $table);
    }
    for which you need PDO (MySQLi as of PHP 5.4)

    why your code (snippet) doeasn’t work is
    - $table is undefined
    - $tables doesn’t change
    - $tableCount does not influence anything

    Comment

    Working...