Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with mysql_fetch_assoc()

Status
Not open for further replies.

ruffy

Programmer
Oct 1, 2003
72
US
I have code that fills variables for replacement into the contents of a .tpl file,
and then echoes the result.

Here's the code that determines the $p1 value:

<?php
...
$myinfo = mysql_fetch_assoc($result);
// fetch the 1st prospect
if ($myinfo["filler1"] == NULL) {
$p1 = $myinfo["fname"]." ".$myinfo["lname"];
} else {
$p1 = $myinfo["filler1"];
}

$p2 = "2";
$p3 = "3";
...
$tmp = @file_get_contents("file_x.tpl");
$tmp = str_replace(array("%%p1%%","%%p2%%",...), array($p1, $p2, ... ), tmp);
echo $tmp;
?>

Were I to hardcode $p1 = "xyz";, then the $p1 value would display.
But by deriving its value from the mysql_fetch_assoc function,
the value remains blank.


Any help would be appreciated.
 
try
Code:
if (is_null($myinfo["filler1"])) {

if that does not work then echo the output of your row to the screen to debug

Code:
echo "<pre>".print_r($myinfo, true) ."</pre>";
 
Your "is_null" code changes nothing;
It's just another way to code my if statement.

If I were to write, just before the $p2="2" code:
"echo $p1;"
the screen would display the correct string value,
as your suggestion of print_r verified.
It's only when the value gets placed into the input field
that it displays a blank.
If, instead of the if logic, I simply write
$p1 = "1";
Then I WOULD see this value show up in my input field!
There's something about the mysql_fetch_assoc function that's blocking its appearance (I think).
 
there is a difference between == and === that might explain why I suggested is_null()

my understanding is that with == there is an implicit conversion of the type (null) to a string. This is what i take from the manual anyway. thus an empty field would (wrongly) be considered null.

if, as you say, the correct value of the row is being determined then there must be something wrong with your comparison, rather than the mysql_fetch_assoc.

furthermore you say that if you echo $p1 after the comparison before $p2 is set, then it has the value you wish.

so unless I am misunderstanding your reply, the problem must be in your template str_replace or your template itself.

I'm assuming that it's a typo but of course missing out the variable identifier '$' in the third parameter of your str_replace function would be a killer.
 
You're probably right, in that it has either to do with the str_replace or the template.
But I see no problems with either, because they both seem to work correctly.
I include them here in case I'm blind to something I did wrong.

indexTST.php

<?php
include_once "config.php";
if (!isset($_POST['sessDate']) ) {
$s1 = date("m/d");

$result = mysql_query("SELECT * from Prospect WHERE listid=\"CF01\"", $dbh);
if (!$result) exit('Failed to get resultset 2');
$myinfo = mysql_fetch_assoc($result);

if (is_null($myinfo["syn"])) {
$p1 = $myinfo["fname"]." ".$myinfo["lname"];
} else {
$p1 = $myinfo['syn'];
// echo $myinfo['syn'];
}
// echo "<pre>".print_r($myinfo, true) ."</pre>";
$p1 = (string) $myinfo['syn'];
// $p1 = "111";
}
$tmp = @file_get_contents("tst.tpl");
$tmp = str_replace( array("%%s1%%", "%%p1%%"), array($s1, $p1), $tmp);
echo $tmp;
?>

tst.tpl

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "<html xmlns=" xml:lang="en" lang="en">
<head>
<title>TST Screen</title>
<link rel="stylesheet" href="tst.css" type="text/css" />
<script language="JavaScript" src="tst.js" type="text/javascript"></script>
</head>
<body>
<form name="fhpp">
<div id="session">
<fieldset>
<legend>SESSION</legend>
<label>Date</label>
<input name="sessDate" type="text" value="%%s1%%" size="5" />
</fieldset>
</div>
<div id="prospect">
<fieldset>
<legend>PROSPECT</legend>
<label>Name</label>
<input name="pname" type="text" value="%%p1%%" size="25" />
</fieldset>
</div>
</form>
</body>
</html>
 
agreed that nothing looks wrong. try adding some debug in and getting rid of the extra $p1 setting.

Code:
<?php
include_once "config.php"; 
if (!isset($_POST['sessDate']) )  {    
	$s1 = date("m/d");
	$result = mysql_query("SELECT * from Prospect WHERE listid=\"CF01\"", $dbh);
	if (!$result) exit('Failed to get resultset 2');
	if (mysql_num_rows($result) === 0 ) die ('no rows are returned');
	$myinfo = mysql_fetch_assoc($result);
	if (is_null($myinfo["syn"])) {
		$p1 = $myinfo["fname"]." ".$myinfo["lname"];
	} else {
		$p1 = $myinfo['syn'];
//    echo $myinfo['syn'];
	} //end if
// echo "<pre>".print_r($myinfo, true) ."</pre>";
//  $p1 = (string) $myinfo['syn']; //this has been commented out as mysql will translate all output into strings other than NULL
// $p1 = "111";
}
$tmp = @file_get_contents("tst.tpl"); 
$tmp = str_replace( array("%%s1%%", "%%p1%%"), array($s1, $p1), $tmp);
echo $tmp;    
?>

but this is not the best way of form filling (IMO). If you're not fixed on this method, post back and i'll provide an example of a different way.
 
I'm always willing to learn jpadie. Will appreciate if you'll show me a better way to form-fill.
 
In fact, I don't even know the advantage of the tpl way.
Is it because it hides the source view from the browser, or what?
 
Is it because it hides the source view from the browser, or what?

not really. i suspect it is a matter of personal choice. designers may opt for the template method becomes it carries the most chance of keeping the design integrity true. coders would probably take the opposite approach: at its purest to abstract the form construction completely to a separate class (take a look at HTML_QuickForm in the pear repository).

here is an example of how I might fully handle a form. there is no right or wrong here. it's just a different method
Code:
<?php
//set up some variables
$minAge = 18;
$maxAge = 110;
ini_set('display_error', 'on');
error_reporting(E_ALL);

if (isset($_POST['submit'])){
	if(true === ($result = validateForm())){
		displayOKMessage();
	} else {
		displayForm($result, $_POST);
	}
} else {
	displayForm();
}

function displayOKMessage(){
	echo "Hello.  Your data was validly received.  Your inputs were: <br/><pre>".print_r($_POST,true) . " </pre>";
	echo "<br/>";
	echo <<<HTML
	click <a href="{$_SERVER['PHP_SELF']}">here</a> to try again
HTML;
}

function validateForm(){
	global $minAge, $maxAge;
	$return = '';
	//dummy validation rules
	if (empty($_POST['name'])){
		$return .= "<p>You must enter a name</p>";
	}elseif(strlen($_POST['name']) < 4){
		$return .= "<p>Your name is too short...</p>";
	}
	
	if(empty ($_POST['age'])){
		$return .= "<p>You must submit an age</p>";
	}elseif ($_POST['age'] < $minAge || $_POST['age'] > $maxAge){
		$return .= "<p>Your age is out of the permissible range</p>";
	}
	return (empty($return)) ? true : $return;
}
function displayForm($message = null, $values = array()){
	
	
	//set up the variables for the form
	$name = '';
	$age = 18;
	
	//override input values if we are loading the form with edit values
	//clean them up first
	$values = array_walk($values, 'cleanse');
	extract($values);
	
	//format the options for use
	$options = getAgeOptions($age);
	
	//errors?
	if (!empty($message)){
		echo <<<HTML
<div class="errorMessage" style="color:red; background-color:silver; border:thin solid black;margin-bottom:5px;">
$message
</div>

HTML;
	}
	echo <<<HTML
<form method="post" action="{$_SERVER['PHP_SELF']}">
<fieldset>
Type your name: <input type="text" name="name" value="$name"/><br/>
Select your age: <select name="age">{$options}</select><br/>
<input type="submit" name="submit" value="submit"/>
</fieldset>
</form>
HTML;
}

function getAgeOptions($value){
	global $minAge, $maxAge;
	$options ='';
	for ($i=$minAge; $i<=$maxAge; $i++){
		$selected = ($value == $i) ? "selected=\"selected\"" : '';
		$options .= <<<HTML
	<option value="$i" {$selected}>$i</option>

HTML;
	}
	return $options;
}

function cleanse($value){
	if (get_magic_quotes_gpc()){
		$value = stripslashes($value);
	}
	return trim($value);
}
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top