When I try to run this code it will not insert the data into the database?
<?php
class Database {
private $dsn;
function __construct($dbname, $host, $user, $password, $enckey) {
$this->dsn = "mysql:dbname=" . $dbname . ';host=' . $host;
$this->user = $user;
$this->password = $password;
}
private function createDSN() {
return $this->dsn;
}
public function createConnection() {
try {
$dbh = new PDO(self::createDSN(), $this->user, $this->password);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
}
$db = new Database('mytest', 'localhost', 'root', 'hashedpassword', null);
$dbh = $db->createConnection();
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
?>
I don't get an error message
but you have to get it. Asking other people about your database makes very little sense.
Asking the database itself is a way better idea.
add this line to your createConnection() (I dunno what this function for but as you have it)
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
and run your code this way
try {
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
} catch (PDOException $e) {
echo $e->getMessage();
}
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 3 years ago.
users.php:
'''
class users {
private $id;
private $name;
private $email;
private $login_status;
private $last_login;
private $db_conn;
function setID($id){ $this->id = $id; }
function getID($id){ return $this->id; }
function setName($name){ $this->name = $name; }
function getName($name){ return $this->name; }
function setEmail($email){ $this->email = $email; }
function getEmail($email){ return $this->email; }
function setLoginStatus($login_status){ $this->login_status = $login_status; }
function getLoginStatus($login_status){ return $this->login_status; }
function setLastLogin($last_login){ $this->last_login = $last_login; }
function getLastLogin($last_login){ return $this->last_login; }
public function __construct() {
require_once("db_conn.php");
$db = new db_conn();
$this->db_conn = $db->connect();
}
public function save() {
$sql = "INSERT INTO users ('id', 'name', 'email', 'login_status', 'last_login') VALUES (null, :name, :email, :login_status, :last_login)";
$stmt = $this->db_conn->prepare($sql);
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":login_status", $this->login_status);
$stmt->bindParam(":last_login", $this->last_login);
try{
if($stmt->execute()){
return true;
}else{
return false;
}
}catch(Exception $e){
echo $e->getMessage();
}
}
}
'''
db_conn.php
'''
class db_conn{
private $host = 'localhost';
private $db = 'webapp';
private $user = 'root';
private $pass = '';
public function connect(){
try{
$conn = new PDO('mysql:host=' . $this->host . '; db=' . $this->db, $this->user, $this->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch(PDOException $e){
echo 'Database Error: ' . $e->getMessage();
}
}
}
?>
'''
When I run my file, it shows error like this :
I have update my code, but now it shows error like SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected.
I have search at Stackoverflow but still not find the right solution. Please help me.
Your code must use backticks for all columns and not apostrophes
$sql = "INSERT INTO `users` (`id`, `name`, `email`, `login_status`, `last_login`)
VALUES (null, :name, :email, :login_status, :last_login)";
For your Problem with no database selected check your connection string, if there is a Databasename .
But you can always send a sql query
use Databasename;
Or use the correct sy code instead old db= it must be dbname=
class db_conn{
private $host = 'localhost';
private $db = 'webapp';
private $user = 'root';
private $pass = '';
public function connect(){
try{
$conn = new PDO('mysql:host=' . $this->host . '; dbname=' . $this->db, $this->user, $this->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch(PDOException $e){
echo 'Database Error: ' . $e->getMessage();
}
}
You have single quotes arround table name users
Change this line :
$sql = "INSERT INTO 'users' ('id', 'name', 'email', 'login_status', 'last_login');
To :
$sql = "INSERT INTO users (id, name, email, login_status, last_login) VALUES (null, :name, :email, :login_status, :last_login)";
I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm setting to do a simple query using PDO. However, when I run it, it does not insert. The database is called "famous" and the table is called "pessoas" containing only two columns called (codigo and nome).The connection works, but when I execute it return "Error to save".
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;bdname=pessoas';
$user = 'root';
$password = 'init4289';
try{
$pdo = new PDO($dsn, $user, $password);
echo 'SUCESSO AO CONECTAR!';
return $pdo;
}catch(PDOExeption $ex){
echo 'erro: '. $ex->getMessage();
}
}
?>
#end page "conexao_pdo.php"
<?php
include 'conexao_pdo.php';
$conn = getConnection();
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if($stmt->execute()){
echo 'Success to save';
}else{
echo '<p>'.'Error to save';
}
?>
You may consider the following:
probably it's just a typing error - bdname should be dbname in 'mysql:host=localhost;bdname=pessoas'
database and table names - 'famous' and 'pessoas' in the question, 'pessoas' and 'famous' in the code
include exception handling with PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
your function getConnection() should return false on failure
Code, based on your question:
<?php
function getConnection(){
$dsn = 'mysql:host=localhost;dbname=pessoas';
$user = 'root';
$password = 'init4289';
try {
$pdo = new PDO(
$dsn,
$user,
$password,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
echo 'SUCESSO AO CONECTAR!';
} catch (PDOExeption $ex){
echo 'Error: '. $ex->getMessage();
return false;
}
return $pdo;
}
?>
<?php
include 'conexao_pdo.php';
// Connection
$conn = getConnection();
if ($conn === false) {
exit;
}
// Statement
try
$sql = "INSERT INTO famosos (codigo, nome) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, 6);
$stmt->bindValue(2, 'Antonio');
if ($stmt->execute()) {
echo 'Success to save';
} else {
echo '<p>'.'Error to save';
}
} catch (PDOExeption $ex){
die ('Error: '. $ex->getMessage());
}
?>
class dbConnection {
function connect(){
try{
$this->db_conn = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", $this->db_user, $this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
}
class student{
public $link;
public function __construct(){
$db_connection = new dbConnection();
$this->link = $db_connection->connect();
return $this->link;
}
public function checkLogin($username,$password){
$query = $this->link->prepare("SELECT * FROM studentprofiles where UserName = :uname AND LogPassword = (select md5(:upassword));");
$query->execute(array(':uname' => $username, ':upassword' => $password));
$count = $query->rowCount();
if($count === 1){
$this->setSession($username);
}
return $count;
$query = null;
}
public static function display(){
$query = $this->link->prepare("SELECT ForeName, Surname FROM studentprofiles where UserName = :uname;"); //getting error here: Fatal error: Using $this when not in object context
$query->execute(array(':uname' => self::getSession()));
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
printf (" <span id='WelcomeName'> Welcome: %s %s\n </span>",$row[0],$row[1]);
}
$query = null;
}
}
Error using $this again to prepare another select statement, how do I use it again for another function in the same class? Thank You
Appreciate any help, really stuck on this problem
hi you can check you code and i prefer asign in to value the conection example
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
and in your function you make some one how this
function connect(){
try{
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
in a complete example this:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
please try and good luck
So really I just want to make stuff easier to read and just create a function where I can call upon the database connection, the below is what i've tried to do to do far.
So far, it doesn't work, it doesn't bring any message at all so presumably it isn't going into the try.
functions.php
function getDBConnection()
{
try
{
$db = new PDO('mysql:host=localhost;dbname=name;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Set error mode
}
catch(PDOException $e)
{
echo 'An error occured talking to the DB';
}
return $db;
}
and then do
submittest.php
require('functions.php');
getDBConnection(); //return $db
$username = 'donkey';
$password = 'donkey';
$email = 'donkey';
$county = 'donkey';
try
{
//Prepare and execute an insert into DB
$st = $db->prepare("INSERT INTO users(login,pass,email,county) VALUES(:username,:password,:email,:county)");
$st->execute(array(':username' => $username, ':password' => $password, ':email' => $email, ':county' => $county));
echo 'Success';
}
catch (PDOException $e)
{
echo 'An error occurred talking to the DB';
}
?>
$db = getDBConnection(); //return $db