Why am I getting these errors? php and mysql - php

ERROR CODE:
Notice: Undefined variable: blog_array in
/home/willconnor/public_html/index.php on line 69
* create the blog array */$blog_array = array();
<?php
if(sizeof($blog_array) > 0)
{
/*** loop over the blog array and display blogs ***/
foreach($blog_array as $blog)
{
echo '<div class="blog_entry">';
echo '<p><span class="category">'.$blog['blog_category_name'].': </span>
<span class="blog_date">Added by '.$blog['blog_user_name'].' on '.$blog['blog_content_date'].'</p>';
echo '<h2>'.$blog['blog_content_headline'].'</h2>';
echo '<p>'.$blog['blog_content_text'].'</p>';
echo '</div>';
}
}
else
{
echo 'No Blogs Here';
}
/*** include the footer file ***/
include 'includes/footer.php';
?>
ERROR CODE:
Warning: mysqli_select_db() expects parameter 1 to be mysqli, string given in /home/willconnor/public_html/includes/conn.php on line 16
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** connect to the database ***/
$link = mysqli_connect($hostname, $username, $password);
/*** select the database ***/
$db = mysqli_select_db('blog', $link);
?>

try as follows
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
$con=mysqli_connect($hostname,$username,$password,"blog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
and if you want to change the selected database "blog" then only you need to write following line
mysqli_select_db($con,"replace_selected_db");

Actually you could pass the name of the database as the fourth parameter in mysqli_connect() function, like this:
<?php
$hostname = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'blog';
$link = mysqli_connect($hostname, $username, $password, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error();
}
?>

You connection should code like:
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** database ***/
$my_db = 'blog';
/*** connect to the mysql and select database ***/
$link = mysqli_connect($hostname, $username, $password, $my_db);
/*** Check connection ***/
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
After this you can check for your $blog_array.
Hope this help!

You need to use connection parameter($link) as first parameter for mysqli_select_db() function. Just replace your code with below.
<?php
/*** mysqli hostname ***/
$hostname = 'localhost';
/*** mysqli username ***/
$username = 'username';
/*** mysqli password ***/
$password = 'password';
/*** connect to the database ***/
$link = mysqli_connect($hostname, $username, $password);
/*** select the database ***/
$db = mysqli_select_db($link, 'blog');
?>

Related

I am trying to retrieve data from my database using PDO Fetch object

I am trying to retrieve data from my database using PDO Fetch object and it says
Fatal error: Uncaught Error: Call to undefined method mysqli_result::execute()
what I'm doing wrong
This is what I have tried
<?php
$servername = "localhost"; $username = "root"; $password = ""; $dbname = "messages_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$getquery = $conn->query('select col_name from db where id = 2');
$getquery->execute();
$result = $getquery->fetch(PDO::FETCH_OBJ);
?>
<div><?= $result->col_name; ?></div>
Firstly, don't mix PDO and mysqli. Stick to one. Here's a PDO example. You first need to create a new PDO object. and connect to DB at the start
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "dbname";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername,
$dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
$rtrv = "select col_name from db where id = 2"
$stmt = $pdo->prepare($rtrv);
//Execute.
$stmt->execute();
//Fetch.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
// Do whatever you want after this

How to connect MySQL db using new XAMPP

Old connection method mysql_connect maybe deprecated from PHP7 so what is the best way to connect and query in mysql using XAMPP or how I implement PDO in my bellow script.
<?php
$key = $_GET['key'];
$array = array();
$con = mysql_connect("localhost", "root", "");
$db = mysql_select_db("search", $con);
$query = mysql_query("select * from ajax_example where name LIKE '%{$key}%'");
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row['name'];
}
echo json_encode($array);
?>
Database connection using mysqli_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
For further mysqli_* statement syntax refer: Mysqli_* Manual
Database connection using PDO_* :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
For further PDO_* statement syntax refer PDO_* Manual
$conn = new Connection();
$query = "select * from ajax_example where name LIKE '%{$key}%'";
$res = $conn->execute_query($query)->fetchall(PDO::FETCH_ASSOC);
if (!empty($res))
{
$result['data'] = $res;
echo json_encode($result);
}

Need help connecting my database to PHP

I am trying to connect my database to my PHP code using this code:
<html>
<head>
<title>Landing page</title>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<?php
// Check if username and password are correct
if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") {
// If correct, we set the session to YES
session_start();
$_SESSION["logged_in"] = "YES";
echo "<h1>You are now logged in</h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
else {
// If not correct, we set the session to NO
session_start();
$_SESSION["logged_in"] = "NO";
echo "<h1>You are NOT logged in </h1>";
echo "<p><a href='secure1.php'>Link to protected file</a></p>";
echo "<p><a href='secure2.php'>Link to protected file #2</a></p>";
}
?>
<p>Public Page</p>
<p>Logout</p>
</body>
</html>
Instead of using the inline username and password, I would like to use the databases username and password from a specific table. I just cant get it to work for some reason, and I am finding it really hard. It would be great if anyone could help.
Note:
You have to establish first a connection to your database. Replace the necessary data inside the connection
I used mysqli_* prepared statement rather than deprecated mysql_*
Replace your if ($_POST["username"] == "logintest" && $_POST["password"] == "access123!") { with if($checklog > 0 ){
Code:
/* ESTABLISH FIRST YOUR CONNECTION TO YOUR DATABASE */
$con = new mysqli("host", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT Username, Password FROM user_login WHERE Username = ? AND Password = ?")){
$stmt->bind_param("ss",$_POST["username"],$_POST["password"]);
$stmt->execute();
$stmt->store_result();
$checklog = $stmt->num_rows;
if($checklog > 0){
/* HERE IS YOUR CODE WITH SUCCESSFUL LOGIN */
}
else {
/* HERE IS YOUR CODE WITH UNSUCCESSFUL LOGIN */
}
$stmt->close();
}
There are several ways to connect to MySQL. However, just knowing how to connect isn't enough. You need to learn how to use it as well. Therefor I'm first giving you a couple of links to MySQLi and PDO:
PHP: MySQLi - Manual
PHP: PDO - Manual
Now to answer your question, here are some commonly used methods to connect to mysql:
MySQLi Object Oriƫntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
MySQLi Procedural Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_error()){
echo "Failed to connect to MySQL: (" . mysqli_connect_error() . ")";
}
?>
PDO Object Oriƫntated Style
<?php
$dbhost = ""; //Server Address
$dbname = ""; //Database Name
$dbuser = ""; //Database User
$dbpass = ""; //Database Password
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>

php mysql connection get error message

this is my first php code , i am trying to connect to a database with user name = "root" and password = "root"
i have a connection file called dbConnection.php
as following :
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
and i call it in a file called what.php :
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
this returns status code 500 which is internal server error
but i want to know what is the error to fix it how can i get the error message ?
i tried
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
but it is not returning any thing.
can any one help me please ?
if you are having password on localhost then use password otherwise leave it blank
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
You mysqli_connect() method.
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
First Thing is to Change your connection method to mysqli or my personal favorite PDO.
PDO Example:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
Then you can extend your PDO class to new classes after including the db.php page.
Example Select:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// make the current db
$db_selected = mysqli_select_db ( $conn , $dbname );
if (!$db_selected) {
die ('Can\'t connect to Database : ' . mysql_error());
}
?>

Function for connecting to mysql database

I made my first function for connecting to mysql database. I have index.php and functions.php and i included functions.php to index.php!
This is my Connect to database function...
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1", $username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
}
return $dhb;
}
I don't know is it correct and if i am calling it right.
I type in index.php
<?php
require_once 'functions.php';
connect_to_database();
active_links();
include 'includes/head.php';
include 'includes/nav.php';
..................
See comments:
function connect_to_database()
{
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
$dbh = false; // initialized for error
try {
$dbh = new PDO("mysql:host=$hostname;dbname=zadatak1",
$username, $password);
/*** echo a message saying we have connected ***/
/**echo 'Connected to database';**/
}
catch(PDOException $e)
{
echo $e->getMessage();
// consider to exit / throw own exception / stop continuing script anyhow ....
}
// returns false on error
return $dbh; // typo here, was $dhb !!
}
Usage:
$DB = connect_to_database();
if ( $DB !== false )
$DB->function();
So it works fine now, here is the answer! Thank you for help
I created file named config.php
// PDO connect *********
function connect()
{
$host = 'localhost';
$db_name = 'database_name';
$db_user = 'root';
$db_password = '';
return new PDO('mysql:host='.$host.';dbname='.$db_name, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
and just calling connect function like this, $pdo = connect(); or any name for var but that is the way!
<?php
include 'config.php';
$pdo = connect();
........

Categories