Jump to content

Problem with making a function display


kpetsche20

Recommended Posts

Hey, I'm trying to make a function so I don't have to keep writing while loops. Anyway I cannot get any information to display. I dont think the variable is being send to the function because nothing displays when I run the code.

 

 

index.php

<?php

include("functions.php");

$par="users";

mywhile($par);

?>

 

loop.php

<?php 

function mywhile($par)
{


	$sql = "SELECT * FROM ".$par."";
	$sql = mysql_query($sql);
	while($data = mysql_fetch_array($sql))
		{
		$name = $data['name'];
		}
		echo $name;

}


?>

Link to comment
https://forums.phpfreaks.com/topic/115664-problem-with-making-a-function-display/
Share on other sites

do u have error reporting even on???

 

Cause u say the file with the function is loop.php

but you include functions.php

 

you should have a call to undeclared function error if that is how it is.

 

Also you echo is outside the while loop in the function meaning that the echoed $name is only the last $name in the series of rows

Also you fail to check if there is any rows returned using mysql_num_rows on the query resouce

 

Overall this is poor programing with no really net gain

if there's an error in mysql why won't it display

 

<?php 

function mywhile($par)
{


	$sql = "SELECT * FROM ".$par."";
	$sql2 = mysql_query($sql2) or die(mysql_error());
	while($data = mysql_fetch_array($sql2))
		{
		$name = $data['name'];
		echo $name;
		}


}


?>

better way to write your pointless function

<?php
function mysql_display($query){
$q = mysql_query(mysql_real_escape_string($q)) or die(mysql_error()."<br /><br />".$q);
if(mysql_num_rows($r) >0){
	while($row = mysql_fetch_assoc($r)){
		print_r($row);
	}
}
else{
	return FALSE;
}
}

#example
mysql_display("Select * from `Users`");
?>

Since cooldude832 being an ass.

<?php 
function mywhile($par)
{
	$sql = "SELECT * FROM ".$par.""; //make sure if $par comes from a user that at some point you sanitize it to prevent SQL injections
                $result = mysql_query($sql, $link);
                if(!$result){return 0;}   //doing this so that when you call the function you can do if(!mywhile()){//do if query failed}{//do if query passes}
	while($data = mysql_fetch_array($sql2))
		{
		$name = $data['name'];
		echo $name;
		}
}
?>

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.