Use a function declared in a different file [PHP-HTML] - php

Good morning,
i'm trying to make a responsive web page, though the combined use of Html5, css3 and php 7.2 (configured with microsoft SqlServer-2008-R2, because the company has the database stored there yet).
Now, i'm trying to make it modular, so i want to have:
Home.php (with the html structure of the page),
Styles.css (with the style of the page),
Classes.php (with all the declarations of classes and functions that Home.php can call and use while needed, like OpenConnection etc...).
The problem is that i can't call the functions from the classes.php file.
I'm trying to open the connection to our server but it doesn't work.
this is my actual code for the Classes.php file:
<?php
class Connessioni {
function apriConn ($srv, $db){
/* Get UID and PWD from application-specific files. */
$uid = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\uid.txt");
$pwd = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\pwd.txt");
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$db);
try {
$conn = new PDO( "sqlsrv:server=".$srv.";Database = ".$db, $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
return $conn;
}
?>
and this is how i call it from the Home.php:
<table class="w3-table-all w3-hoverable w3-card-4 ">
<?php
require (classes.php);
$serverName = "xxx.xxx.x.x";
$database = "EDP";
$conn= apriConn($serverName, $database);
$query = "My query, that it does work, i've used it yet directly in sql server";
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
</table>
Can you please help me ?
thank you so much.

Related

Verify if connection to the mySQL exists or let Apache do it

I created a function to connect to the db in php:
function fn_connect($is_write = false)
{
$host = '127.0.0.1';
$db = 'name_db';
if ($is_write) {
$user = 'user_write';
$pwd = 'password_write';
} else {
$user = 'user_read';
$pwd = 'password_read';
}
$conn = new mysqli($host, $user, $pwd, $db);
if ($conn->connect_error) {
die('The database is not available. Please, try again later.');
}
return $conn;
}
When I need to connect, im calling it (and closing it) like this
$conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
$conn->close();
I thought it will be a good idea to verify if the connection exists, that way, I guess, I save connecting to the db every time for nothing, like this:
if (!isset($conn)) $conn = fn_connect(true);
$stmt = $conn->prepare($q);
$stmt->execute();
....
$stmt->close();
if (isset($conn)) $conn->close();
Is this a good idea, a good practice? Should I jut connect normally and let Apache/PHP do the rest (no need to verify nothing)?
It is good practiose and good style to check the connection, before letting php try to get or send data.
What is not good style is to use die in your connection, because it leaves a broken page.
Better is to design the page so that page still works when the connection is broken.

How to fix server error 500 when executing PHP script?

I am trying to insert into a database through PHP. However, when I connect to the PHP file I get server 500 error. Would anyone be able to spot what I am doing wrong?
<?php
include 'db-security.php';
function db_login()
{
$userName = filter_input(INPUT_POST, "userName");
$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$statement = $link->prepare("INSERT INTO user(username, password)
VALUES($userName, $password)");
//execute the sql statement.
$statement->execute();
}
db_login();
?>
Updated:
I have discovered the error occurs when i add filer_input or $_post to the php.
<?php
include 'db-security.php';
function db_login() {
global $conn;
// use my eaxmple to filter input to get the data out of the form, because security.
//$userName = filter_input(INPUT_POST, "userName");
$userName = $_POST['userName'];
$password = $_POST['password'];
//$password = filter_input(INPUT_POST, "password");
//binding the variable to sql.
$stmt = $conn->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
//execute the sql statement.
}
db_login();
?>
db-security.php
<?php
include_once 'conf.php';
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $conn;
// Try and connect to the database, if a connection has not been established yet
if(!isset($conn)) {
// Load configuration as an array. Use the actual location of your configuration file
try
{
$conn = new PDO("mysql:host=localhost;port=3307;dbname=database", DB_USERNAME,DB_PASSWORD);
// stores the outcome of the connection into a class variable
$db_msg = 'Connected to database';
}
catch(PDOException $e)
{
$conn = -1;
$db_msg = $e->getMessage();
}
//$conn = new PDO(DB_HOST,DB_USERNAME,DB_PASSWORD , MAIN_DB);
}
}
db_connect();
?>
Where is $link defined? In 'db-security.php'? If yes then you have a variable scope problem. Just pass $link in the function call. This would have to be done for all functions.
define function as = function db_login($link)
call function like = db_login($link);
EDIT:
Don't use a function for 'db-security.php' it should be like this:
<?php
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
This is not complete code, just a sample. Now $conn is in the global variable scope and using global in the functions will work. Or just pass $conn to the function and not use global at all.
EDIT2:
Below are the working sample scripts. You need to change some information to match your setup. I'm not sure why the function is called db_login() since the function actually adds the user/password into the 'user' table.
conf.php
<?php
define('DB_USERNAME', 'test');
define('DB_PASSWORD', '123456');
?>
db-security.php
<?php
include_once 'conf.php';
try
{
$conn = new pdo("mysql:host=localhost; dbname=test; charset=utf8", DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
die('Unable to connect to database!');
}
?>
main script
<?php
include 'db-security.php';
function db_login()
{
global $conn;
$userName = $_POST['userName'];
$password = $_POST['password'];
$stmt = $conn->prepare("INSERT INTO user(username, password) VALUES(:usrname, :pswd)");
$stmt->bindParam(':usrname', $userName);
$stmt->bindParam(':pswd', $password);
$stmt->execute();
}
db_login();
?>
So you need to bind your parameters after prepare statement
$stmt = $link->prepare("INSERT INTO user(username, password)VALUES(:usrname, :pswd)");
$stmt->bindParam(':pswd', $password);
$stmt->bindParam(':usrname', $userName);
$stmt->execute();
I have been looking at your code and I would advice you to try a different approach. I've been wrapping my head around this subject for a while when learning PHP. Best advice i've had is that you can best try when fetching information from the DB is using a try/catch statement everytime. Sounds annoying or problematic but it easy to overlook and well written maintained code because you know every try catch block will execute or catch the error atleast.
With PDO being one of the best solutions because it can connect with multiple databases the best way to execute getting information from the Database is this:*
I am gonna give you my example of something i wrote. I don't want to write it all out in your situation because i feel that's something you can better do to learn what went wrong and i hope this gives you a step in the right direction.
database.php
$serverName = "";
$dbName = "";
$userName = "";
$password = "";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password);
// Set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
}
catch(PDOException $e){
echo"Connection failed: " . $e->getMessage();
exit;
}
?>
index.php Executing a simple commmand get firstName from employers
<?php
require_once 'database.php';
try
{
$sQuery = "
SELECT
firstName
FROM
employees
";
$oStmt = $db->prepare($sQuery);
$oStmt->execute();
while($aRow = $oStmt->fetch(PDO::FETCH_ASSOC))
{
echo $aRow['firstName'].'<br />';
}
}
catch(PDOException $e)
{
$sMsg = '<p>
Regelnummer: '.$e->getLine().'<br />
Bestand: '.$e->getFile().'<br />
Foutmelding: '.$e->getMessage().'
</p>';
trigger_error($sMsg);
}
?>
Good luck and i hope my index.php is helpful in showing you how I find is the best way momentarily to talk to the database.

PHP and MySQL Nested database connection

This is a general example.
The application has 3 files.
conn.inc.php -- setting up the database connection
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
func.inc.php -- file including functions
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
?>
index.php -- the main page to display content
<?php
include 'conn.inc.php';
include 'func.inc.php';
if (!isset($_GET['page_name'])) { // if page_name is not set then reset it to the homepage
$page_name = 'module_footer';
}else{
$page_name = $_GET['module_footer'];
}
$module_content = load_module($page_name);
echo $module_content;
?>
Now my goal was to include functions inside the func.inc.php file and database into conn.inc.php, so as to keep separate and easier to read in the future.
My problem now is that the $conn variable declared in conn.inc.php cannot be used inside the function and it can't get my head around how to use it. I even tried using GLOBALS with no success.
The error for the files is this:
Notice: Undefined variable: conn in ./func.inc.php on line 4
Fatal error: Call to a member function query() on a non-object in ./func.inc.php on line 4
Which (I assume) is because the $conn variable is not in a global scope.
Now my question is. How can I keep the nested files but have the functions working? Is there a mistake in my approach or is it not possible to use a nested call to a mysql object?
Eventually you'll want to get into object-oriented coding but for now lets make what you have a little prettier.
When including files, you'll want to avoid things like global variables. They sound great, but end up being a pain when handling scope. So instead include a set of functions to call.
conn.inc.php
function getConnection(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
Then function.inc.php
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
//Here is where we get our database connection.
$conn = getConnection();
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
And finally finish up with your index page the way it is. So now, any page that wants a database connection will need to include the conn.inc.php and simply call getConnection() to get a mysqli connection object.
Think of your program as being a series of individual functions working together. And eventually you'll get to it being a series of objects working together. Nothing should be just floating off in global space. Try to encapsulate everything in some sort of function or object to be called over and over with consistent results.
You'd have to do something like this:
$conn = '';
function connect() {
global $conn;
... do db stuff
}
But this is usually bad practice. A more common method is to use a singleton object to "carry" your db handle, and you new that singleton everywhere you need to do DB operations.
function do_something() {
$conn = new DBSingleton();
... do db stuff
}

Uncaught exception 'PDOException' message 'invalid data source name'

I´m trying to connect to my database with PDO and show some blogposts on a page.
However I´m getting this error message:
Fatal error: Uncaught exception 'PDOException' with message 'invalid
data source name' in index.php on line 61...
I´ve been searching for help but really can´t figure out what is wrong so if anyone have any idea it is much appreciated!
I have a separate connect.inc.php file which is included in the index.php file.
This is the connect.inc.php file:
<?php
class DB extends PDO
{
function database_connection() {
$db_host = "localhost";
$db_name = "blogdata";
$db_user = "username";
$db_pass = "password";
try {
global $db_host, $db_name, $db_user, $db_pass;
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
}
catch(PDOException $e) {
die( 'Query failed: ' . $e->getMessage() );
}
}
}
?>
And this is the section in the index.php file which is pointed out in the error message:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$query = "SELECT * FROM blogposts";
if ($result = $db->query($query)) {
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo '
<section id="content">
<article class="post_title"><h3> ', $row['title'],' </h3></article>
<article class="post_message"> ', nl2br ($row['message']),' </article>
<article class="post_time"> ',$row['time'],' </article>
</section>
';
}
} ;
?>
Gotcha.
For some reason you are extending your class from PDO. So, your 'blogdata' is taken as a DSN.
Just get rid of your DB class and use raw PDO
connect.inc.php:
<?php
$db_host = "localhost";
$db_name = "blogdata";
$db_user = "username";
$db_pass = "password";
$db = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
index.php:
<?php
require 'connect.inc.php';
$query = "SELECT * FROM blogposts";
$result = $db->query($query);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
Why are you declaring your DB variables global after initialising them? I can't test it but if memory serves that'll pull in existing values from global, overwriting the ones you've just declared.
I disagree with not using an inherited class though - being able to write a custom constructor means you can set all modes and attributes once and then just call the custom constructor to have it done automatically. Much cleaner than having to do it every time.
For future references, you could keep the DB class and refer to the following solution that hasn't much to do with the php class:
enter link description here

Call to a member function query() on a non-object on trying to read data

Hi I have been learning php from this book PHP Solutions Dynamic Web Design Made Easy and gotten to the part where I have to work with mysqli api for databases.After writing a connection function and running the script I get this error:
This is my code:
function dbConnect($usertype , $connectionType = 'mysqli'){
$host = 'localhost';
$db = 'phpsols';
if($usertype == 'read'){
$user = 'psread';
$pwd = 'Aleczandru1989';
}elseif($usertype == 'write'){
$user = 'aleczandru';
$pwd = 'Aleczandru1989';
}else{
exit('Unrecognized type');
}
if($connectionType == 'mysqli'){
return new mysqli($host , $user , $pwd , $db) or die ('Cannot open database');
}else{
try{
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
} catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
}
$conn = dbConnect('read');
$sql = 'SELECT * FROM images';
$result = $conn->query($sql) or die(mysqli_error()); //Line 5
$numRows = $result->num_rows;
Line 5 in this case refers to $result = $conn->query($sql) or die(mysqli_error());.
What Am I doing wrong here?
The $conn object you are attempting to create with dbConnect('read'); fails. If you would do a var_dump($conn); it probably shows it is not what you aspect it to be. The error is actually describing what is wrong. You try to access the query function with '->query(..' on $conn. But $conn has to be an object reference that actually has the query function. The points where this object will be created are:
return new mysqli($host , $user , $pwd , $db)
and
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
Since you are showing a different error then
or die ('Cannot open database');
My guess it is actually gong wrong at
return new PDO("mysql:host=$host;dbname=$db", $user, $pwd);
And you will catch the exception. But the echo statement is not visible anymore due to the fatal error. You will have to do some debugging there!
I have no experience with PDO, but construction of the object seems ok. (but can this help you out: http://nl1.php.net/manual/en/class.pdo.php#84751) If the construction is ok, than check if your database engine is actually running :) ?

Categories