Requesting assistance regarding basic php PDO connection - php

(Disclaimer:
This code is from Chapter 11 of the book "PHP Solutions: Dynamic Web Design Made Easy" Copyright David Powers, 2006. It is a great resource in my opinion, speaking from the perspective of an obviously very novice web developer. Here is the source code for the entire book. Some of this code is a bit different from what is in the book itself. )
** edit: corrected code according to first comment by Benny Hill.
** edit for Solution: case closed, with the help of Benny Hill.
Solution: After correcting my code, I had to manually direct the browser to the file: http:// localhost/siteG/mysql/pdo.php (<-- this is correct), versus dragging the file straight into the browser, producing this URL: file:///C:/wamp/www/siteG/mysql/pdo.php This is what was messing me up. Thank you Benny Hill.
Hello,
I am having trouble connecting to my DB with the following code.
Here is what my browser outputs:
query($sql); $error = $conn->errorInfo(); if (isset($error[2])) die($error[2]); // find out how many records were retrieved $numRows = $result->fetchColumn(); echo $numRows; ?>
Here is the code :
Connection File: conn_pdo.inc.php
<?php
// call this function like this: $conn=dbConnect('admin') or, admin can be query
function dbConnect($type) {
if ($type == 'query') {
$user = 'root';
$pwd = 'root';
}
elseif ($type == 'admin') {
$user = 'root';
$pwd = 'root';
} else {
exit('Unrecognized connection type');
}
}
function dbConnect() {
try {
$conn = new PDO('mysql:host=localhost;dbname=basicgallery', $user, $pwd);
return $conn;
}
catch (PDOException $e) {
echo 'Cannot connect to database';
exit;
}
} ?>
the "query" file: pdo.php
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<?php
include('../includes/conn_pdo.inc.php');
// connect to MySQL
$conn = dbConnect('query');
// Prepare sql query
$sql = 'SELECT COUNT(*) FROM images';
// submit the query and capture the result
$result = $conn->query($sql);
$error = $conn->errorInfo();
if (isset($error[2])) die($error[2]);
// find out how many records were retrieved
$numRows = $result->fetchColumn();
echo $numRows;
?>
</body>
</html>
Can anyone help me figure out why the browser is outputting raw php code?

Your conn_pdo.inc.php file should look like this:
<?php
// call this function like this: $conn=dbConnect('admin') or, admin can be query
function dbConnect($type){
if ($type == 'query'){
$user = 'root';
$pwd = 'root';
}
elseif ($type == 'admin'){
$user = 'root';
$pwd = 'root';
}else{
exit('Unrecognized connection type');
}
try{
$conn = new PDO('mysql:host=localhost;dbname=basicgallery', $user, $pwd);
return $conn;
}
catch (PDOException $e){
echo 'Cannot connect to database';
exit;
}
}
?>
I removed the second declaration of dbConnect and the closing brace for the first declaration of dbConnect.

Related

form values will not save into PhpMyAdmin or MYSQL workbench is something wrong with my connection to the database

this is the code i am using to send data to phpmyadmin from my squidgameeditor3.php and insert2.php pages.
squidgameeditor3.php
<form action="insert2.php" method="POST" target="votar">
insert3.php
<?php
//Database Credentials
$host = 'localhost:3306';
$database = 'circulartexter';
$username = 'root';
$password = '';
try {
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password); }
catch(PDOException $e) {
echo "did catch that! ";
echo $e->getMessage(); }
echo " #it works";
$sz1 = $_POST['sz1'];
$tp1 = $_POST['tp1'];
$lh1 = $_POST['lh1'];
$ft1 = $_POST['ft1'];
$sp1 = $_POST['sp1'];
$sh1 = $_POST['sh1'];
$sk1 = $_POST['sk1'];
$ma1 = $_POST['ma1'];
$sql = "INSERT INTO atrmain (`sz1`,`tp1`,`lh1`,`ft1`,`sp1`,`sh1`,`sk1`,`ma1`) SELECT ('$sz1','$tp1','$lh1','$ft1','$sp1','$sh1','$sk1','$ma1')";
?>
phpmyadmin
i looked everywhere cant find the answer but i know its simple because i had this code working on another laptop before but it wont work on my new laptop so as soon as i get this question answered i will delete it

PDO/PHP LoginScript ending in error 500 using MAMP

I've been trying for a while now to get my loginscript working and i can't seem to find the issue, either im just blind or there's something else going on here.
It doesn't matter if i input the correct credentials or not into the form, i still end up getting a lovely error 500.
Any ideas?
The DB connect funtion:
function db_connect() {
if i move this column-->
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
<---
return $conn; /added this as suggested, still returns NULL.
}
The login file:
include('../lib/functions.php'); //This is correct!
db_connect();
<-- HERE, it works -->
Earlier had an issue where my password hash during register was faulty, so password_verify($_POST['password'], $results['passw'])had no effect, always returning false even with correct input.
if(!empty($_POST['username']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT uname,passw FROM users WHERE uname = :user AND passw = :pass');
$records->bindparam(':user', $_POST['username']);
$records->bindparam(':pass', $_POST['password']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
if(count($results) > 0 && password_verify($_POST['password'], $results['passw']) && $_POST['username'] == $results['uname']) //Also tried removing the &&-->username area incase two and statements were wrong without any luck {
die('It works!');
} else {
die('OR NOT!');
}
endif;
Your db_connect() function defines $conn in it's own scope. So, variable $conn is local. And after db_connect() ends executing $conn just disappears.
Outside this function $conn is simply NULL.
Return $conn to outer scope from your function:
function db_connect() {
$server = 'localhost';
$uname = 'root';
$passw = 'password';
$datab = 'database';
/* check connection */
try{
$conn = new PDO("mysql:host=$server;dbname=$datab;", $uname, $passw);
} catch(PDOException $e) {
die( "Connection failed: " . $e->getMessage());
}
return $conn; // here
}
And in your script:
include('../lib/functions.php'); //This is correct!
$conn = db_connect();
// other codes

php page doesn't rendering when connect to database

I'm making simple php web page, using php5, mysql, Nginx.
when connect to database, it suddenly freeze, and render nothing to browser..
my php code is this.
<?php
$host = 'localhost';
$user = 'root';
$password = '123456';
$db_name = 'test';
$link = new mysqli($host, $user, $password, $db_name);
if($link->connect_errno) {
echo "<script>alert('Connection Error....')</script>";
}
if($link) {
echo "<script>alert('Successfully connected!');</script>";
}
?>
(lib/connect_db.php)
<?php
include './lib/connect_db.php';
$create_user_query = 'CREATE TABLE ...';
$admin_user_query = 'INSERT INTO ....';
$create_widget_query = 'CREATE TABLE ...';
if($link->query($create_user_query) === TRUE) {
echo "<script>alert('Success!')</script>";
}
$link->close();
?>
(init.php)
index.php also include './lib/connect_db.php', it is OK. but init.php always causing problem.
p.s. when I edited init.php to
<script>alert('...');</script>
<?php
...
?>
it doesn't call alert();
you have syntax error you missing $ before variable in (lib/connect_db.php)
include '.lib/connect_db.php';
$create_user_query = 'CREATE TABLE ...';
$admin_user_query = 'INSERT INTO ....';
$create_widget_query = 'CREATE TABLE ...';
if($link->query($create_user_query) === TRUE) {
echo "<script>alert('Success!')</script>";
}
$link->close();

XML request MySQL by PHP

Actually i'm working in a flash web page using XML. I want to make a sing up page with XML that uses PHP to insert data into de MySQL database, but I'm stuck... and i my XML-PHP knowledge are not enough for this duty.
This is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<data>
<title>Sing up</title>
<request field1="user" field2="email" field3="password" field4="other">reg.php</request>
<description><![CDATA[Please sing up!]]></description>
</data>
The reg PHP file:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$con = mysql_connect($dbhost, $dbuser, $dbpassword);
if (!$con)
{
die('Could not connect!');
} else {
mysql_select_db("$logondb", $con);
$sql="INSERT INTO accounts (username, sha_pass_hash, email) VALUES ('$user','$pass','$email')";
if (!mysql_query($sql,$con))
{
die('Error creating account.');
}
echo $succesmsg;
mysql_close($con);
}
} else {
?>
And PHP conf for database:
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpassword = 'password';
// Accounts Database
$logondb = 'accounts';
$errormsg="Error creating account..";
$succesmsg="Account created!";
?>
I would like to suggest using PDO instead - it's a more general approach. And then you should use data-binding to reduce vulnerability against SQL Injections...
This should take you one step further:
<?php
function Reg()
{
if (isset($_POST['reg'])==true) {
require_once('./db_conf.php');
$user = $_POST['username'];
$pass = sha1(strtoupper($user.':'.$_POST['password']));
$email = $_POST['email'];
$dsn = "mysql:host=$dbhost;dbname=$logondb";
$pdo = new PDO($dsn,$dbuser,$dbpassword);
if (!$pdo)
{
die('Could not connect!');
} else {
$sql = "INSERT INTO accounts (username, sha_pass_hash,email) VALUES (:user,:pass,:email)";
$stmt = $pdo->prepare($sql);
$res = $stmt->execute(array("user"=>$user , "pass"=>$pass , "email" => $email));
if (!$res) {
echo "Error :((<pre>";
var_dump($stmt->errorInfo());
echo "</pre>";
} else
{
echo $succesmsg;
}
}
} else {
echo "reg was not set - terminating...!";
}
}
Reg(); // execute it!
?>

MySQL connect on PHP

what is the best way to connect PHP application on MySQL.
So far I had the below connection classes.
class Connection{
private static $server = "127.0.0.1";
private static $catalog = "schemadb";
private static $username = "rootuser";
private static $password = "password";
public static $current = null;
public static function Open(){
self::$current = mysqli_init();
if(!self::$current){
die("Failed to initialize connection");
}
if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
die("Cannot connect to server");
}
return self::$current;
}
public static function Close(){
self::$current->close();
}
}
and also I have
abstract class abstractDAO
{
protected function getConnection()
{
$mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
return $mysqli;
}
}
or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..
You can try using the PDO object:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
Have a look at PHP PDO documentation page
Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate.
You just need to enter your database configuration like give in below
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';
You can connect through data using PDO, here is an example
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
try {
$conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
$stmt = $conn->prepare("SELECT * FROM todolist");
$stmt->execute();
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table border="1" align="center">
<tr>
<th>name</th>
<th>type</th>
<th>status</th>
</tr>
<?php
foreach($stmt->fetchAll() as $k=>$v){
echo
"<tr>
<td>{$v['name']}</td>
<td>{$v['type']}</td>
<td>{$v['status']}</td>
</tr>\n";
}
?>
</table>
</body>
</html>
try this
<?php
$user = $_POST["username"];//if this doesnt work try the next line
$user = (isset($_POST["username"]) ? $_POST["username"] : "");
$host = "localhost";//mysql password
$username = "";//mysql username
$password = "";//mysql password
$db_name = "database";//database name
$tbl_name ="test";//table name
//make the connection
$con = mysql_connect("$host","username","password")or die("Could not connect.");
$conn = mysql_select_db("$db_name")or die("Could not select database.");
$sql = "SELECT * FROM $tbl_name WHERE username='$username'";
//query mysql
$result = mysql_query($sql);
if($result){
//if it works show this
}else{
//if it doesnt work show this
}
?>
ive tryed a lot of times to make a connection to a database and i finaly found one.

Categories