Jump to content
PatrickG19872019

Help with my php/database code

Recommended Posts

Hello, I am trying to get this website working but i get an error saying invalid data source name.

I am fairly certain the error is from one of these 2 files.

db_connection.php

<?php
function OpenCon()
 {
 $dbhost = "localhost";
 $dbuser = "root";
 $dbpass = "123";
 $db = "db";
 $conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
 
 return $conn;
 }
 
function CloseCon($conn)
 {
 $conn -> close();
 }
   
?>

and the other file index.php

/*
// <? /* php require('includes/db_connection.php'); */ ?>
*/
<? php include 'db_connection.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Blog</title>
    <link rel="stylesheet" href="style/normalize.css">
    <link rel="stylesheet" href="style/main.css">
</head>
<body>

	<div id="wrapper">

		<h1>Blog</h1>
		<hr />

		<?php
$db = null;
global $stmt;
			try {
				
				
				// $stmt = db->query('SELECT postID, postTitle, postDesc, postDate FROM blog_posts ORDER BY postID DESC');
				$conn = new PDO('SELECT postID, postTitle, postDesc, postDate FROM blog_posts ORDER BY postID DESC');
				while($row = $stmt->fetch()){
					
					echo '<div>';
						echo '<h1><a href="viewpost.php?id='.$row['postID'].'">'.$row['postTitle'].'</a></h1>';
						echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).'</p>';
						echo '<p>'.$row['postDesc'].'</p>';				
						echo '<p><a href="viewpost.php?id='.$row['postID'].'">Read More</a></p>';				
					echo '</div>';

				}

			} catch(PDOException $e) {
			    echo $e->getMessage();
			}
		?>

	</div>


</body>
</html>

Please help me with this error, I would really like this to work.

Thank you very much.

Share this post


Link to post
Share on other sites

That

$conn = new PDO('SELECT postID, postTitle, postDesc, postDate FROM blog_posts ORDER BY postID DESC');

is not how to use PDO. Check whatever article or tutorial you're learning PDO from to see the right way.

And the first bit of code has nothing to do with the second. It's an attempt to use mysqli, which is fine except the rest of the code is not using mysqli (nor even either function the first defined).

Share this post


Link to post
Share on other sites

I'm sorry I don't understand what you mean. Can you please explain this in more detail. This is from a website that shows your how to create a blog from scratch so i don't have any actual experience with php and don't know how to connect properly.

Share this post


Link to post
Share on other sites

Then you should start learning PHP so you can work with it. Or at least so you can spot when the site you look at for help is doing something wrong - like what they're doing with PDO.

Share this post


Link to post
Share on other sites
On 6/4/2019 at 9:37 PM, PatrickG19872019 said:

...i don't have any actual experience with php...

Are you familiar with other programming languages? Are you looking to know more about PHP? In other words, is this a new responsibility for you? Or maybe this is a short-time thing, where are you just trying to fix something?

Assuming that you are looking to learn, is this a new website...or an established one? If it's new, you should probably dump the MySQLi code and go straight to PDO. If not, it would probably be better to learn more about MySQLi, for now. Assuming that's what your website typically uses. I'm guessing that's the case since your db_connection.php script uses MySQLi for connecting to the database in the OpenCon() function. That way you can learn from the existing database interactions using working examples.

With that said, the call to your database connection script should be imported with "require". The database connection seems pretty crucial to the page being displayed properly. More information about using "require" and the differences between that and "include" can be found here:
https://www.php.net/manual/en/function.require.php

If/when you want to start using PDO, more information about establishing a connection to the database using that interface can be found here:
https://www.php.net/manual/en/pdo.connections.php

Share this post


Link to post
Share on other sites
On 6/4/2019 at 7:37 PM, PatrickG19872019 said:

I'm sorry I don't understand what you mean. Can you please explain this in more detail. This is from a website that shows your how to create a blog from scratch so i don't have any actual experience with php and don't know how to connect properly.

Specifically:
In your db_connection.php, there are 2 function definitions.  You include those --- so great.  But the functions are never called. 

If you look at OpenCon() what does it do?  Well it is trying to make a mysqli_ connection and then returning that.

But in the actual code, you then go on to try and use PDO to make a query.  PDO and MySqli are 2 alternative ways to talk to the database.  You need to pick one.  The code in the db_connection file should be changed to use PDO.  Read through this if you need to crib code.

This will also show you where you went wrong in regards to your actual query.  Your PDO object needs to be instantiated with the credentials you have in your db_connection.

So--- completely untested but generally the right direction would be:

 

//db_connection.php

function OpenCon()
  $host = 'localhost';
  $db   = 'db';
  $user = 'root';
  $pass = '123';
  $charset = 'utf8mb4';

  $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
  $options = [
      PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
      PDO::ATTR_EMULATE_PREPARES   => false,
  ];
  try {
       $pdo = new PDO($dsn, $user, $pass, $options);
       return $pdo
  } catch (\PDOException $e) {
       throw new \PDOException($e->getMessage(), (int)$e->getCode());
  }
}
// Make a global pdo connection variable
$pdo = OpenCon();

So at that point, if the db connection works, you'll have a PDO connection available named $pdo.  

You would need to fix your confused index.php and remove extraneous variables and the attempt to intermix mysqli and pdo:

 

<?php require_once('includes/db_connection.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Blog</title>
    <link rel="stylesheet" href="style/normalize.css">
    <link rel="stylesheet" href="style/main.css">
</head>
<body>

	<div id="wrapper">

		<h1>Blog</h1>
		<hr />

		<?php

			try {
				$stmt = $pdo->query('SELECT postID, postTitle, postDesc, postDate FROM blog_posts ORDER BY postID DESC');
				while($row = $stmt->fetch()){
					
					echo '<div>';
						echo '<h1><a href="viewpost.php?id='.$row['postID'].'">'.$row['postTitle'].'</a></h1>';
						echo '<p>Posted on '.date('jS M Y H:i:s', strtotime($row['postDate'])).'</p>';
						echo '<p>'.$row['postDesc'].'</p>';				
						echo '<p><a href="viewpost.php?id='.$row['postID'].'">Read More</a></p>';				
					echo '</div>';

				}

			} catch(PDOException $e) {
			    echo $e->getMessage();
			}
		?>

	</div>


</body>
</html>

 

Again, I did this quickly so no guarantees are provided.  If it doesn't work outright you may need some debugging of the pdo connection, but it's far closer to what you require.

Make sure you understand the differences between this code and your original code.  Most of what I put in there was pulled directly from the PDO Tutorial I linked.

Share this post


Link to post
Share on other sites
17 hours ago, gizmola said:

The code in the db_connection file should be changed to use PDO.

@PatrickG19872019 - If you decide to go this route, switching your db_connection file to PDO, just be sure to review the rest of your website first. If there are other pages using db_connection and MySQLi, switching to PDO will break those pages. To prevent breaking existing pages, you could create another function like OpenPDOCon() for all your PDO stuff. Then you can update all your old pages to PDO at your leisure.

Note that your existing CloseCon() function won't work with PDO. You would either need to create a separate function for closing PDO connections...or you could let PHP close the connection for you. Connections are automatically closed when the script is done executing.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×

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.