I have a bunch of mysql queries in my sight that Im going to need to convert to PDO. Can I do this one query at a time and all other functions continue to work? For example if I convert 1 query to PDO with that hinder all my other mysql queries from working properly?
That should work without any problems as long as you have 2 database connections open, one for the mysql_* functions and one for PDO.
The only potential drawback is the temporary extra overhead of the two db connections instead of one.
I don't see why it would, unless you're using some sort of special database handler class or something.
One thing you might want to consider is not using a "connections" script, but using more of an OOP/data-model setup.
Basically, you keep your connection details in a separate file - mine just defined some constants that I could access later in the script in which it gets included. From there, you create a class that is responsible for establishing it's own connection when instantiated. This class will contain methods that correspond to your typical queries, with maybe a method to run a raw query as needed.
The advantage of doing this is that you can basically leave your existing code alone, and just add your new data model code where you want, as you update or replace your existing scripts.
For reference's sake, here's a stripped down version of code I used to use:
db.php
<?php
# Set the database access information as constants.
DEFINE ('DB_USER', 'your_db_user_name');
DEFINE ('DB_PASSWORD', 'your-super-duper-secret-password');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'schema-name');
DEFINE ('DB_CONNECTION', 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME );
?>
blog-model.php
<?php
# File: blog-model.php
# Version: 1.0
# Updated: 2011.9.4
# Meta: This file contains the database access information.
# This file also establishes a connection to MySQL and selects the database.
#require_once( ROOT . DS . 'config' . DS . 'db.php' );
# Utility Class
class BlogModel {
protected $pdo;
# Constructor
function __construct() {
$this->connect();
}
function __destruct() {
}
# Connect to the database
function connect() {
# Database connectivity can be a tricky beast, so I'm wrapping the entire block in a try/catch
try {
$this->pdo = new PDO( DB_CONNECTION, DB_USER, DB_PASSWORD, array( PDO::ATTR_PERSISTENT => true ) );
# Set character set to UTF-8 (adds support for non-ASCII languages).
# Note this can cause issues with BLOB-style fields, especially with INSERTs
$this->pdo->exec( "SET CHARACTER SET utf8" );
return true;
}
catch(PDOException $e) {
# Add code to write out error log and alert administrator
trigger_error( "<p>Could not select the database</p>\n<p>MySQL Error: " . $e->getMessage() . "</p>" );
return false;
}
}
# Run an INSERT query; that is, insert a new row (or rows) into a MySQL table
function insert( $authorid, $title, $permalink, $category, $body, $tags, $abstract ) {
try {
# Named parameters (prefered)
$stmt = $this->pdo->prepare(
"INSERT INTO pages
SET title = :title,
permalink = :permalink,
category = :category,
body = :body,
tags = :tags,
abstract = :abstract,
author = :authorid,
timestamp = NOW();"
);
$stmt->bindParam( ':title', $title );
$stmt->bindParam( ':permalink', $permalink );
$stmt->bindParam( ':category', $category );
$stmt->bindParam( ':body', $body );
$stmt->bindParam( ':tags', $tags );
$stmt->bindParam( ':abstract', $abstract );
$stmt->bindParam( ':authorid', $authorid, PDO::PARAM_INT );
return $stmt->execute();
}
catch( Exception $e ) {
# Add code to write out error log and email administrator
trigger_error( "<p>An error occurred whilst executing your query:\n<br />MySQL Error: " . $e->getMessage() . "</p>" );
return false;
}
}
# Run an UPDATE query; that is, update an existing row (or rows) in a MySQL table
function update( $id, $title, $category, $body, $tags, $abstract ) {
try {
# Update the project matching the supplied id
# Named parameters (prefered)
$stmt = $this->pdo->prepare(
"UPDATE pages
SET title = :title, category = :category, body = :body, tags = :tags, abstract = :abstract, lastupdated = NOW()
WHERE permalink = :id
LIMIT 1;"
);
$stmt->bindParam( ':id', $id );
$stmt->bindParam( ':title', $title );
$stmt->bindParam( ':category', $category );
$stmt->bindParam( ':body', $body );
$stmt->bindParam( ':tags', $tags );
$stmt->bindParam( ':abstract', $abstract );
return $stmt->execute();
}
catch( Exception $e ) {
# Add code to write out error log and email administrator
trigger_error( "<p>An error occurred whilst executing your query:\n<br />MySQL Error: " . $e->getMessage() . "</p>" );
return false;
}
}
# Run a DELETE query; that is, remove a record (or records) from a MySQL table
function delete( $id ) {
try {
# Delete the project matching the supplied id
# Named parameters (prefered)
$stmt = $this->pdo->prepare( "DELETE FROM pages WHERE id = :id LIMIT 1;" );
$stmt->bindParam( ':id', $id, PDO::PARAM_INT );
return $stmt->execute();
}
catch( Exception $e ) {
# Add code to write out error log and email administrator
trigger_error( "<p>An error occurred whilst executing your query:\n<br />MySQL Error: " . $e->getMessage() . "</p>" );
return false;
}
}
# Close the connection
function close() {
$this->pdo = null;
}
}
?>
This is all probably not entirely relevant to your original question, but maybe you (or some random Google-er) can derive some use from it.
Related
Basically, we are trying to add some values in a database. We are doing it using a GET command to get the value called "valeur" and writing this in the database. However it is not working, the values are not added to the database
<?php
try
{ // connection a la base de donnees
// connection to mySQL
$bdd = new
PDO('mysql:localhost;dbname=test1', 'root', '');
}
catch(Exception $e) //in case of error, display it and stop everything
{
die('Erreur : '.$e->getMessage());
}
if (isset($_GET['temp1'])) // test if the variable exists
{
$_GET['temp1'] = floatval($_GET['temp1']);
echo ('donnee ' .$_GET["temp1"]. ' en cours d\'ecriture</br>');
$bdd->exec('INSERT INTO temp (valeur) VALUES('.$_GET["temp1"].')');
echo ('donnee ' .$_GET['temp1']. ' ecrite!');
}
?>
If we put a value in (in our case) http://localhost/test1/add.php?temp1=(thevalue) then it should be inserted into our table called temp in the column "valeur". Instead, it doesn't write anything.
Edit : We are using PHP version 5.6.19 and MySQL 5.7.11 and WAMPserver
EDIT2: I have finally resolved the problem, though I have no idea how.
Php looks fun
You should assign a variable for the SQL query for debugging target.
And echo to print how is your query string. After that, you paste your $query in SQL tab at Phpmyadmin to know what is your error.
$query = "INSERT INTO temp (valeur) VALUES('.$_GET['temp1'].')";
echo $query;
As you are using PDO it makes sense to utilise some of the strengths of it - primarily in this case prepared statements and bound parameters to make the sql much safer from malicious users.
If you separate the database connection from the remaining code you have a database connection which can be used elsewhere quickly and easily simply by including it at runtime, so the first piece of code below could be the db connection file.
( I see you have solved the problem yourself just before posting this... )
<?php
/*******************
dbo-conn.php
*/
try{
$options=array(
PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_general_ci\', ##sql_mode = STRICT_ALL_TABLES, ##foreign_key_checks = 1'
);
$dbuser='root';
$dbpwd='';
$bdd=new PDO( 'mysql:host=localhost;dbname=test1;port=3306;charset=UTF8', $dbuser, $dbpwd, $options );
}catch( PDOException $e ){
exit( $e->getMessage() );
}
?>
On the page that does the database inserts
<?php
try{
# test that the variable is set and available...
if( !empty( $_GET['temp1'] ) ){
# rudimentary check for number
if( !is_numeric( $_GET['temp1'] ) )throw new Exception( sprintf( 'Supplied parameter "%s" does not appear to be a number', $_GET['temp1'] ) );
$valeur = $_GET['temp1'];
# include the db connection
# the path used here depends where the file `dbo-conn.php` is saved
# - this assumes the same directory
require 'dbo-conn.php';
# generate sql & prepared statement
$sql='insert into `temp` ( `valeur` ) values ( :valeur )';
$stmt = $bdd->prepare( $sql );
# check the prepared statement was created ok before attempting to execute it
if( !$stmt ) throw new Exception( 'Failed to prepare sql "INSERT" query'
# bind the placeholder to the supplied user input
$stmt->bindParam( ':valeur', $valeur, PDO::PARAM_STR );
# commit the query
$result = $stmt->execute();
if( !$result )throw new Exception( 'oops! something went wrong' );
# display a message to the user
printf('donnee %s ecrite!', $valeur );
}
}catch( Exception $e ){
exit( sprintf( 'Erreur: %s', $e->getMessage() ) );
}
?>
if (isset($_GET['ResetPassword'])) {
$name = $_GET['name'];
$sql = "ALTER LOGIN $name WITH PASSWORD=N'Nico1234!'";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $_GET['name'], PDO::PARAM_STR);
$stmt->execute();
}
Hi guys I cant alter the password of a certain name(user) Where the name is from get (Selected from the sql).
Thanks for the help.
ALTER TABLE Statements are used for changing the schema of a Table like adding a Column or FOREIGN KEYS.
Are you trying to make an UPDATE Statement? The right query would be:
"UPDATE Login SET PASSWORD='Nico1234!' WHERE name=:name"
If you want to add the $_GET['name'] Parameter to the statement, you have to use :name anywhere inside it.
If you want to change the properties of a SQL Server login account, use ALTER LOGIN.
The problem here will be the parameter in your statement.
Table and column names cannot be replaced by parameters in PDO. I'm not sure, but I think that it's the same for login names.
So, in this case, you should use statement without parameters, escape special characters and sanitize the data manually.
As a note, when you want to use a parameter, the correct syntax for a placeholder is :name or ?, not $name.
<?php
...
try {
# SQL Authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows Authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
...
try {
$name = $_GET['name'];
$password = 'Nico1234!';
# Escape special characters and do some check for $name and $password values
$stmt = $conn->prepare("ALTER LOGIN $name WITH PASSWORD = N'$password'");
$stmt->execute();
} catch( PDOException $e ) {
die("Error executing query: ".$e->getMessage() );
}
...
?>
ALTER LOGIN needs permissions to execute correctly. If you use Windows authentication, then the Web server's process identity or thread identity (if the Web server is using impersonation) is used to connect to the SQL Server. Use next script for more information (change between SQL and Window authentication):
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'uid';
$pwd = 'pwd';
# PDO Connection
try {
# SQL authentication
#$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
# Windows authentication
$conn = new PDO("sqlsrv:server=$server;Database=$database");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
#
try {
$stmt = $conn->query("SELECT 'SUSER_SNAME' AS [NAME], CONVERT(nvarchar(128), SUSER_SNAME()) AS [VALUE]");
# Data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC) ){
echo $row['NAME'].": ".$row['VALUE']."</br>";
}
} catch( PDOException $e ) {
die( "Error executing query".$e->getMessage() );
}
#
$stmt = null;
$conn = null;
?>
Good morning,
i'm trying to make a responsive web page, though the combined use of Html5, css3 and php 7.2 (configured with microsoft SqlServer-2008-R2, because the company has the database stored there yet).
Now, i'm trying to make it modular, so i want to have:
Home.php (with the html structure of the page),
Styles.css (with the style of the page),
Classes.php (with all the declarations of classes and functions that Home.php can call and use while needed, like OpenConnection etc...).
The problem is that i can't call the functions from the classes.php file.
I'm trying to open the connection to our server but it doesn't work.
this is my actual code for the Classes.php file:
<?php
class Connessioni {
function apriConn ($srv, $db){
/* Get UID and PWD from application-specific files. */
$uid = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\uid.txt");
$pwd = file_get_contents("C:\inetpub\wwwroot\MoviDex\Parametri\UidPwd\pwd.txt");
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$db);
try {
$conn = new PDO( "sqlsrv:server=".$srv.";Database = ".$db, $uid, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
echo "Connected to SQL Server\n";
return $conn;
}
?>
and this is how i call it from the Home.php:
<table class="w3-table-all w3-hoverable w3-card-4 ">
<?php
require (classes.php);
$serverName = "xxx.xxx.x.x";
$database = "EDP";
$conn= apriConn($serverName, $database);
$query = "My query, that it does work, i've used it yet directly in sql server";
$stmt = $conn->query( $query );
while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){
print_r( $row );
}
// Free statement and connection resources.
$stmt = null;
$conn = null;
?>
</table>
Can you please help me ?
thank you so much.
I hope that someone sharp on PHP can help me with problem, that i really don't understand.
I have 2 scripts. 1: test.php 2:functions.php.
I created a little test where i called a functions in functions.php frim test.php and it work fine. I got a return and it was as expected. I also have a third script register.php where i have a query to a database and that work fine.
So I wanted the query to work as a function written in functions.php
Problem: It seems that it won't make the database query! But there is createt a connection
If I move the exactly same query to test.php, it works! Is there some kind of speciel reason for this? I quit new to php, but knows a little about Java, C, JavaScript, Python.
I have checked that my include / require is all in order.
1: test.php:
<?php
require 'includes/functions.php';
$name = 'testuser';
$_ok = 0;
$_ok = check_username ($name);
printf ( 'Navn i database?: ' . $_ok . '<br>' );
?>
2: functions.php:
<?php
require 'includes/db_connect.php';
// Check connection
if (! $mysqli) {
die ( 'mysqli_init_failed' );
}
if (mysqli_connect_errno ()) {
die ( 'Failed to connect to the Database, Sorry..! errorcode: ' .
mysqli_connect_errno() . ' <br>' . 'Error Type: ' . mysqli_connect_error () );
}
if ($debug_mode_c) {
print ('Connection Established: ' . mysqli_get_host_info ( $mysqli ) . '<br>') ;
print ('session_id: ' . session_id ()) . '<br>';
}
// Set HTML-Header to utf-8.
header ( 'Content Type: text/html; charset=UTF-8' );
// Functions
function check_username($_ok) {
$name = 'testuser';
$prep_stmt = "SELECT username FROM customs WHERE username=? LIMIT 1 ";
$stmt = mysqli_prepare($mysqli, $prep_stmt);
mysqli_stmt_bind_param($stmt, 's', $name);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $name_db);
mysqli_stmt_fetch($stmt);
if ($name == $name_db) {
echo "hello";
mysqli_close ($stmt);
$_ok = 0;
} else {
$name = '';
$_ok = 2;
}
mysqli_free_result($stmt);
mysqli_close($stmt);
return $_ok;
}
Maybe found the reason for no query.
Apparently the include script containing establish connection, is not loaded as the function is called in functions.php.
When the query code is in test.php, that include functions.php, all code is read, also the connection for the database.
But even if include 'db_connect' is inside function, it won't work !?! :-(
There is nothing like noquery() function in PHP. please just check it in the include file of the database connection. you will find a user defined function in your include file of the database connection.
I am currently working on an image upload script however I am running into a slight issue when trying to store details of the image into the database.
The upload form grabs the image, checks its details and gets the extension of the image. This works fine however it won't store the image path into the database.
This is the part of the code in question:
$file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
echo $file_path;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "UPDATE user SET img=$file_path WHERE userID = $username";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "file_path", $this->file_path, PDO::PARAM_STR );
$stmt->execute();
if ( $stmt->rowCount() > 0 ) {
echo ('Complete');
}
else {
echo ('Error');
}
}catch( PDOException $e ) {
return $e->getMessage();
}
}
Now the reason I have "echo $file_path;" there was to make sure the values were passing correctly, which they are.
It currently echo's this out if an image is uploaded: images/profile/f1b4edb293.jpg
So everything is working fine, it just failes at the point of actually storing.
Now to further test I even remove the string and path details from the file_path variable and just added a dummy value in there e.g:
$test = "test";
$file_path = $test;
And sure enough, it worked and inserted test into the database.
So that leads me to believe there is an issue with the format of this:
$file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
Any ideas on what part of that is stopping it from saving to the database?
You are injecting PHP strings into your SQL code, thus generating unquoted SQL strings (and opening your script to SQL injection):
$file_path = 'images/profile/' . substr(md5(time()), 0, 10) . '.' . $file_extn;
$sql = "UPDATE user SET img=$file_path WHERE userID = $username";
If you var_dump($sql), you'll see that you are generating invalid SQL. (I wonder why no exception is being thrown.)
However, we see this later:
$stmt->bindValue( "file_path", $this->file_path, PDO::PARAM_STR );
So I guess you are aware of prepared statements but you confusing the place-holder syntax (either :file_path or ?) with PHP's string interpolation ($file_path). Again, you should be getting an exception because you're binding a non-existent parameter :-?
Additionally, you have both $file_path and $this->file_path. One of them is probably a typo.
You need to replace this:
$sql = "UPDATE user SET img=$file_path WHERE userID = $username";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "file_path", $this->file_path, PDO::PARAM_STR );
... with this:
$sql = "UPDATE user SET img=:file_path WHERE userID = :username";
$stmt = $con->prepare( $sql );
$stmt->bindValue("file_path", $file_path, PDO::PARAM_STR );
$stmt->bindValue("username", $username, PDO::PARAM_STR );
use this code
$sql = "UPDATE user SET img=:file_path WHERE userID = :username";
$stmt = $con->prepare( $sql );
$stmt->bindValue( ":file_path", $file_path, PDO::PARAM_STR );
$stmt->bindValue( ":username", $username, PDO::PARAM_STR );
$stmt->execute();
do you not need to have file path like '$newfile' i.e.
$sql = "UPDATE user SET img='$file_path' WHERE userID = '$username'";
It's worth a try ?