Include path issue

Hai folks

script filename : get_position_by_id.php

<?php
function get_position_by_id($position_id){
    include("../includes/pdo_connection.php");
    $query="SELECT * 
            FROM positions
            WHERE position_id='$position_id'" ;
    $result = $db->query($query);
    $row = $result->fetch();
    $position=$row['position'];
    return $position;
}
?>

in my above code, if i open the included file path in dreamviewer by right clicking, it opens.
but when i upload it to ftp, it does not.

Warning: include(…/includes/pdo_connection.php): failed to open stream:

what could be wrong?

sorry folks, i was sorted out this case.

my db connection approach is total wrong. its not related to path, its related to the db connection.
i passed the db handle to the function as parameter and now it works.

function get_position_by_id($position_id,$db){
    .......
}

Glad you have it working, here’s how to do it using prepared statement:

<?php
function get_position_by_id($position_id, $db) {

	$query="SELECT * 
	FROM positions
	WHERE position_id=:id";
	
	/* Prepare the query */
	$stmt = $db->prepare($query);
	
	/* Execute the query with the prepared statement */
	$stmt->execute(array(':id' => $position_id));
	
	/* Fetch the results */
	$result = $stmt->fetch(PDO::FETCH_ASSOC);
	
	/* Return the result */
	return $result['position'];
	
}
1 Like

awesome!

Using prepared statements will help protect you from SQL injection :smile:

A function that makes use of a database connection should receive the database as an argument, otherwise the code is rendered untestable due to outside dependencies. Functions that issue require statements should be few and far between - template parsing functions and class loaders for the most part.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.