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
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

Link to comment
Share on other sites

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`");
?>

Link to comment
Share on other sites

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;
		}
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.