include_once database connection

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

include_once database connection

Post by jaad »

Hey people,

I have a question about the include_once database connection on top of every one of my pages.
I'm not a goober, I'm just new to PHP and trying to learn a few concepts.

I been trying to get a couple of dynamic select box populated from the data in two table in mysql and I'm not getting any results

I been under the assumption since I have an include_once script to connect to my database on top of the page that I don't need to repeat the database connection script again while trying to write a script that would populate my select boxes. Do I need to create another instance of PDO connection to my database prior to write a query and the following PDO::Fetch_assoc() function to get my select box populated?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: include_once database connection

Post by Celauran »

Hard to say without seeing any code. Anything in the included script should be available to you after the include call. Does the include script call a function? Does the function return a value? Have you run var_dump against that value?
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: include_once database connection

Post by jaad »

ok so if it is included then I know I have a good connection since everything else works on the form. yes I have tried to do a var_dump() and I get a blank, nothing. I'm going to keep trying..... Been at this all day lol.
Last edited by jaad on Sun Jan 19, 2014 9:43 pm, edited 1 time in total.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: include_once database connection

Post by Celauran »

Is error reporting turned on? Could you be getting a fatal error farther up the chain? var_dump should always produce output.
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: include_once database connection

Post by jaad »

nope I get zip, blank, nothing.... I have just created a blank page with a the same include_once() db connection and just performed a simple select query and it works fine. so I have a problem on my page, and I bet this problem is the same problem that inhibits me from exploding my value in three different fields, populating my checkbox and select drop down box.

That's what I hate about these tutorial scrip you pick up online.... some weird bug in it and you go crazy thinking that you are doing it all wrong while its not even your fault lol
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: include_once database connection

Post by Celauran »

You can post some code and we'll take a look, or you can start inserting some echo statements to determine where things fall apart and work from there.
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: include_once database connection

Post by jaad »

gosh I really appreciate the offer to help me with the codes, but let me ask you? You and I been exchanging messages for a while now.... I;m pretty sure you have a good feeling that I'm basically incompetent at writing codes and that would be a fair assessment. The thing with me posting my codes and trying to get them to work is not useful for me because the underlining goal I want to accomplish is learn. So far I have uploaded my codes at every step of the way when I tried adding elements to this already built mochup of a website that I picked in a tutorial. I took a leave of absence from work for the whole week in order to get this darn thing to work. I'm really dedicated! you have no idea to what extent I go to put as much time as I can with this. I sleep about 4 hours and work 20 hours on codes, reading and google and tutorial here and there. Why am I having so much trouble? is this normal? I am a fairly intelligent guy; English isn't my first language but I manage. Do you think the best thing for me to do is to drop this damn mochup site that has a lot of the functionality that I need and start from scratch instead? This is really important for me. I really want to succeed at this and I am willing to do anything. what do you suggest I do?



this is the code by the way

Code: Select all

function buildOptions($array)
				{
						$output = '';
						foreach ($array as $key => $value) 
						{
							$output .= '<option value="' . $key . '">' . $value . '</option>' . PHP_EOL;
						}
						return $output;
						}

					$list = array();
					$sql = 'SELECT `id`, `building` FROM `buildings`;';
					foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
					$list[$row['id']] = $row['building'];
				}


<select name="data[country1]" >
							<!-- Use the output from database to build a list of options -->
							<?php echo buildOptions($list); ?>
						</select>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: include_once database connection

Post by Celauran »

Frustrating though it may be at times, this is a really important process. Debugging is an invaluable skill and the better you become at it, the more trivial many of your roadblocks will become. It's also a potentially great learning tool in that it allows you to see exactly what didn't work and to discover why.

Code: Select all

$list = array();
$sql = 'SELECT `id`, `building` FROM `buildings`;';
foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
$list[$row['id']] = $row['building'];
}
This is where I'd start. $list is clearly an empty array at the start. What is it at the end? var_dump and see what it contains.

Code: Select all

$list = array();
$sql = 'SELECT `id`, `building` FROM `buildings`;';
foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
	$list[$row['id']] = $row['building'];
}
var_dump($list);
If it's still an empty array, var_dump your $row inside the loop. Do they contain the expected values?

Code: Select all

$list = array();
$sql = 'SELECT `id`, `building` FROM `buildings`;';
foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
	var_dump($row);
	$list[$row['id']] = $row['building'];
}
No? Move your query out of the foreach and see what that yields.

Code: Select all

$list = array();
$sql = 'SELECT `id`, `building` FROM `buildings`';
$result = $pdo->query($sql, PDO::FETCH_ASSOC);
var_dump($result);
This iterative working backwards should show you exactly where the failure occurs.
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: include_once database connection

Post by jaad »

i get nothing! lol every step of the var_dump() climbing up the script. it's blank

the one thing that might be suggestive is that I loose all the elements on my form after the select box element.

Code: Select all

				function buildOptions($array)
				{
						$output = '';
						foreach ($array as $key => $value) 
						{
							$output .= '<option value="' . $key . '">' . $value . '</option>' . PHP_EOL;
						}
						return $output;
						}

					$list = array();
					$sql = 'SELECT `id`, `building` FROM `buildings`;';
					foreach ($pdo->query($sql, PDO::FETCH_ASSOC) as $row) {
					$list[$row['id']] = $row['building'];
				}
				
					
					
					
									
			$users->update_user($first_name, $middle_name, $last_name, $gender, $dob, $sin, $home_phone, $cell_phone, $emerg_name,$emerg_email, $emerg_phone, $co_app, $co_name, $bio, $image_location, $user_id);
					header('Location: settings.php?success');
					exit();
				
				} else if (empty($errors) === false) {
					echo '<p>' . implode('</p><p>', $errors) . '</p>';	
				}	
            }
			
    		?>
         <form action="" method="post" enctype="multipart/form-data">
    		<h2>"Apply for a Unit - Personal Information."</h2> 
            <p><ul>
            		<li>  <h4>Choose Building:</h4>
					
	                        <select name="data[country1]" >
							<!-- Use the output from database to build a list of options -->
							<?php echo buildOptions($list); ?>
						</select>
	                    </li>
               		
               </ul>
            </p>
            <hr />
FROM HERE________________________________________________________________ - ____________________ ___________ everything below this line does not show on the page.  If I comment the function buildOptions($array) everything gets back to normal
            
                <div id="profile_picture">
                
               		<h3>Change Profile Picture</h3>
                    <ul>
                        
        				<?php
                        if(!empty ($user['image_location'])) {
                            $image = $user['image_location'];
                            echo "<img src='$image'>";
                        } 
                        ?>
                        
                        <li>
                        <input type="file" name="myfile" />
                        </li>
                        <?php if($image != 'avatars/default_avatar.png'){ ?>
	                        <li>
	                            <input type="checkbox" name="use_default" id="use_default" /> <label for="use_default">Use default picture</label>
	                        </li>
	                        <?php 
                        }
                        ?>
                    </ul>
                </div>
            
            	<div id="personal_info">
	            	<h3 >Change Profile Information </h3>
	                <ul>
	                    <li>
	                        <h4>First name:</h4>
	                        <input type="text" name="first_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['first_name']) ){echo htmlentities(strip_tags($_POST['first_name']));} else { echo $user['first_name']; }?>">
	                    </li> 
                         <li>
	                        <h4>Middle name:</h4>
	                        <input type="text" name="middle_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['middle_name']) ){echo htmlentities(strip_tags($_POST['middle_name']));} else { echo $user['middle_name']; }?>">
	                    </li>  
	                    <li>
	                        <h4>Last name: </h4>
	                        <input type="text" name="last_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['last_name']) ){echo htmlentities(strip_tags($_POST['last_name']));} else { echo $user['last_name']; }?>">
	                    </li>
	                    <li>
	                        <h4>Gender:</h4>
	                        <?php
	                       	 	$gender 	= $user['gender'];
	                        	$options 	= array("undisclosed", "Male", "Female");
	                            echo '<select name="gender">';
	                            foreach($options as $option){
	                               	if($gender == $option){
	                               		$sel = 'selected="selected"';
	                               	}else{
	                               		$sel='';
	                               	}
	                                echo '<option '. $sel .'>' . $option . '</option>';
	                            }
	                        ?>
	                        </select>
	                    </li>
                         <li>
	                        <h4>D.O.B (YYYY-MM-DD:</h4>
	                        <input type="date ('yyyy-mm-dd')" name="dob" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['dob']) ){echo htmlentities(strip_tags($_POST['dob']));} else { echo $user['dob']; }?>">
	                    </li>
                        <li>
	                    	
							<h4>SIN: </h4>
	                        <input type="text" name="sin" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['sin']) ){echo htmlentities(strip_tags($_POST['sin']));} else { echo $user['sin']; }?>">
                        </li>
                        <li>
	                        <h4>Home Phone:</h4>
	                        <input type="text" name="home_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['home_phone']) ){echo htmlentities(strip_tags($_POST['home_phone']));} else { echo $user['home_phone']; }?>">
	                    </li> 
                        <li>
	                        <h4>Cell Phone:</h4>
	                        <input type="text" name="cell_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['cell_phone']) ){echo htmlentities(strip_tags($_POST['cell_phone']));} else { echo $user['cell_phone']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency Name:</h4>
	                        <input type="text" name="emerg_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_name']) ){echo htmlentities(strip_tags($_POST['emerg_name']));} else { echo $user['emerg_name']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency email:</h4>
	                        <input type="text" name="emerg_email" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_email']) ){echo htmlentities(strip_tags($_POST['emerg_email']));} else { echo $user['emerg_email']; }?>">
	                    </li>
                        <li>
	                        <h4>Emergency Phone:</h4>
	                        <input type="text" name="emerg_phone" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['emerg_phone']) ){echo htmlentities(strip_tags($_POST['emerg_phone']));} else { echo $user['emerg_phone']; }?>">
	                    </li><br />
                        <li>
	                        	<h4>Co-Application:</h4>
                          <?php  $co_app 	= $user['co_app'];
	                        	$options 	= array("YES", "NO");
	                            echo '<select name="co_app">';
	                            foreach($options as $option){
	                               	if($co_app == $option){
	                               		$sel = 'selected="selected"';
	                               	}else{
	                               		$sel='';
	                               	}
	                                echo '<option '. $sel .'>' . $option . '</option>';
	                            }
	                        ?>
	                        </select>
                                                   
                             <h4>Co-Applicant Name:</h4>
	                        <input type="text" name="co_name" onKeyPress="return disableEnterKey(event)" value="<?php if (isset($_POST['co_name']) ){echo htmlentities(strip_tags($_POST['co_name']));} else { echo $user['co_name']; }?>">
	                    </li><br />
                        <li>
	                        <h4>If you would like to tell us more about yourself:</h4>
	                        <textarea name="bio"><?php if (isset($_POST['bio']) ){echo htmlentities(strip_tags($_POST['bio']));} else { echo $user['bio']; }?></textarea>
	                    </li>
	            	</ul>    
            	</div>
            	<div class="clear"></div>
            	<hr />
            		<span>Update Changes:</span>
                    <input type="submit" value="Update">
               
            </form>
User avatar
jaad
Forum Commoner
Posts: 95
Joined: Fri Jan 03, 2014 5:30 am
Location: Vancouver Canada

Re: include_once database connection

Post by jaad »

here is the test page I made to see if there is anything wrong with my connect script or database and it works fine

Code: Select all

<?php 
$config = array(
	'host'		=> 'localhost',
	'username' 	=> 'root',
	'password' 	=> '1122334',
	'dbname' 	=> 'lar'
);
$id = 5;
try {
$db = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'], $config['username'], $config['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $db->prepare('SELECT `id`,`building` FROM `buildings`');
    $stmt->execute(array('id' => $id));
  
    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}



	


?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<?php 	echo $row;?>
</body>
</html>

Result on page is this

Code: Select all

Array ( [id] => 4 [0] => 4 [building] => The Banff [1] => The Banff ) 
as we would expect
Post Reply