Cannot display table record in html page - html

I am trying to call a record from a table into html to create an admin page so the content can be updated. I cannot get the record to come up. I am totally new to this so any help is appreciated. My table name is tblContent and my database name is data1. I have only one row in the table with a PageID of 1.
home.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php echo mysql_result($rs,0,”PageTitle”);?></title>
<link rel="stylesheet" type="text/css" href="origstyle.css">
</head>
<body>
<div id="container">
<h1>Site Heading</h1>
<?php
require_once 'classes.php';
try {
$conn = new PDO("mysql:host=$host;db_name=$db_name", $db_username, $db_password);
$rs = mysql_query("getData");
echo mysql_result($rs,0,”Content”);
} catch (PDOException $pe) {
die("Could not connect to the database $db_name :" . $pe->getMessage());
}
?>
</div>
</body>
</html>
classes.php
<?php
//Enter your database connection details here.
$host = 'localhost'; //HOST NAME.
$db_name = 'XXXXdbName'; //Database Name
$db_username = 'XXXXuserName'; //Database Username
$db_password = 'XXXXpass'; //Database Password
try
{
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
}
catch (PDOException $e)
{
exit('Error Connecting To DataBase');
}
class database
{
function __construct($pdo)
{
$this->pdo = $pdo;
}
function getData()
{
$query = $this->pdo->prepare('SELECT * FROM data1');
$query->execute();
return $query->fetchAll();
}
}
?>

There's quite a lot of little issues that stop this code from working.
The biggest is that you are trying to use two different database libraries. There's the deprecated mysql library which has all the functions starting with mysql_ and then there's PDO. Replace all the mysql functions with their PDO counterparts.
The next thing I notice is that you seem to be thinking that you pass a method name to the querying function (mysql_query"myData"), but you do not. You call the method on an instance of the class. First you create an instance, like you did for the PDO object, and then you call a method.
$database = new database()
$rs = $database->getData()
The third thing I noticed is that you are creating the PDO object twice. There's no need to create the instance in home.php, so just get rid of that (along with the try/catch stuff related to it).
The fourth thing is minor. You should also capitalize your class names.
Put these together, and you get something like this:
home.php:
require_once "classes.php";
$rs = $database->getData();
// Code that turns $rs into HTML
// Sorry, I don't know PDO well enough to
// say what that is.
// I do know that a simple echo will not suffice.
classes.php:
$host = "localhost"
$db_name = "";
$db_username = "";
$db_password = "";
class Database {
function __construct($pdo) {
$this->pdo = $pdo;
}
function getData () {
$query = $this->pdo->prepare('SELECT * FROM data1');
$query->execute();
return $query->fetchAll();
}
}
try {
$pdo = new PDO('mysql:host='. $host .';dbname='.$db_name, $db_username, $db_password);
} catch (PDOException e) {
exit('Error Connecting To DataBase');
}
$database = new Database($pdo);

Related

How can we start a connection in mysql and php

Can anyone tell me about how to build a connection between mysql and php page.
Please help me with this.
To start a connection You Might do Following code:-
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$dbname = "test";
//change test with your server details//
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn)
{
//echo "connection ok";
}
else
{
echo "connection Failed";
}
?>
hope this code would help you .
Make conn.php file with this code inside and use $conn variable to prepare queries using prepared statement
if(!defined("connection")){
header('Location:error.php');
exit();
}
define("host","localhost");
define("user","mysql_user");
define("pass","password");
define("dbname","database_name");
$conn=new mysqli(host,user,pass,dbname);
if($conn->connect_error){
die("Failed to connect");
exit();
}
mysqli_set_charset($conn,"utf8mb4");
Use conn.php and $conn variable like this
Page.php
require_once("conn.php");
if($stmt = $conn->prepare($query)){
echo "prepared";
}

Function to get mysql results in PHP 7

I'm struggling with the following problem. Some years ago, I've written a function to retrieve MYSQL results (multiple rows). Till PHP7, this code worked fine:
function MultipleRows($query)
{
global $dbhost, $dbname, $dbuser, $dbpass;
mysql_connect($dbhost, $dbuser, $dbpass)
or die("Error! Couldn't <b>Connect</b>.");
mysql_select_db($dbname)
or die("Error! Couldn't <b>Select database</b>.");
$result = mysql_query($query)
or die("Error! Couldn't execute query.");
if(($result)&&(mysql_num_rows($result)>0))
{
return $result;
} else {
return false;
}
mysql_close();
}
Now in PHP7, this code doesn't seem to work anymore. After a lot of searching I came up with this as a replacement but unfortunately it doesn't work:
function MultipleRows($query)
{
$mysqli = new mysqli($dbhost, $dbpass, $dbuser, $dbname);
$result = mysqli_fetch_all($mysqli->query($query), MYSQLI_ASSOC);
return $result;
$mysqli->close();
}
The function is meant to work with code like this:
$res_test = MultipleRows("SELECT id, name FROM table");
if($res_test)
{
while($res = mysql_fetch_array($res_test))
{
echo $res['id'].' '.$res['name'];
}
}
It's not a good option to rewrite the 'display code' (last fragment) because in that case I have to rewrite many lines in my website. Who can give me some help in this? Thanks in advance!
mysql extension has been dropped from PHP 7, after being deprecated in PHP 5.x.
You could rewrite function MultipleRows() using mysqli as follows:
function MultipleRows($query)
{
global $dbhost, $dbpass, $dbuser, $dbname;
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$result = $mysqli->query($query);
if ($result !== FALSE)
$result = $result->fetch_all(MYSQLI_ASSOC);
$mysqli->close();
return $result;
}
A few remarks:
it is not a good idea to use global variables ($dbhost, $dbuser, $dbpass and $dbname)
this way of handling database queries makes you vulnerable to SQL injection attacks

Creating database connection in module.php file zf2

I have a onBootstrap method in module.php file. I want to use this function to also store user log details into the mysql db. Not able to use persist and flush methods. Any thoughts, how to create a db connection?
Thanks in advance
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$eventManager->attach('finish', array($this, 'outputCompress'), 100);
$e->getApplication()->getEventManager()->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
$controller = $e->getTarget();
$app = $e->getApplication();
$sm = $app->getServiceManager();
$auth = $sm->get('zfcuser_auth_service');
$routeMatch = $e->getRouteMatch();
// $name = $auth->getresolvedIdentity('id');
//echo "<pre>"; var_dump($auth); var_dump($routeMatch);
if($routeMatch && $auth){
$Userlog = new Userlog();
$Userlog->setUserid(10);
$Userlog->setUsername('abc');
$Userlog->setUrl_loaded('xyz');
$this->getObjectManager()->persist($Userlog);
$this->getObjectManager()->flush();
}

Login only first user error

Iam using the php 5.5 and pdo to create login code. the code is working fine but the only first user is loged in I don't know why? for example I have 5 user in my database table. when I login the first one then it goes to logedin but when I try to login the 2nd or 3rd one then it will show an error message which I set on incorrect data login. Below is my login code...
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>
Thanks in advance...
You are missing a WHERE CLAUSE :
SELECT * FROM signup WHERE Username = :user
adjust your code to the following:
$smt=$conn->prepare("SELECT * FROM signup WHERE Username =:user");
$smt->execute(array(':user'=>$user));
Please update your code with below code
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup WHERE username = '".$user."' AND password = '".$pass."' ");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>

Working with PDO object - MySQL

I am new to PDO and I have pretty simple question. I have a simple function for connecting to DB:
function connectDB()
{
try {
$dbh = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->exec("SET CHARACTER SET utf8");
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
After calling this function I successfully connect to db. Later when trying to send a query using $dbh->query I got "Call to a member function query() on a non-object ". I do understand that - I don't have an instance of the class at the moment. But the only think to achieve that is to use $dbh = new PDO("settings") again, which is kind of stupid isn't? The function has no sense than. I tried to return the $dbh in the connectDB function (before the NULL statement) but it wasn't really working.
How should be this done properly?
It depends on your app's architecture, but I believe, you should make database handle a class variable, initialize it in constructor and use it later.
class DatabaseAccess{
private $_db;
public function __construct(){
try {
$this->_db = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$this->_db->exec("SET CHARACTER SET utf8");
//notice I removed "= null" part
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
public function getSomething(){
//run your query here:
return $this->_db->query('');
}
}
You need to remove the $dbh = null; sentence in your function. With this sentence you are overwriting the connection with a null value, so anytime later you do $dbh->query(), it's like doing null->query(), and so that error appears.
Also, you need to save the handler, or it gets lost after your code exits that function. Add a return $dbh; at the end of your function or wrap it in a class.