INSERT INTO doesn't write anything in the database - php

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() ) );
}
?>

Related

Unable to alter SQL using PDO statement

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;
?>

UPDATE VARBINARY(MAX) column in SQL Server table with $_FILE image upload

I've been looking all across the internet for help on this and have found nothing.
Basically I need to know how to update a SQL Server VARBINARY(MAX) column with the hex of an image uploaded from a HTML form. The database is in a different place to the HTML form, so move_uploaded_file in PHP then OPENROWSET (BULK ...) in SQL doesn't work (unable to find the file).
I also tried doing file_get_contents on the uploaded $_FILE['name_']['tmp_name'], then used unpack("H*hex") and put the result of that into the SQL column with a "0x" prepend, but that crashes, saying it needs to be converted from a VARCHAR to a VARBINARY. When I convert it, the code runs and the column is populated, but the image is malformed.
No idea what to do next. Pls help.
Solution:
This is a basic approach using PHP Driver for SQL Server:
Table creation (T-SQL):
CREATE TABLE [dbo].[ImageTable] (
[ImageData] varbinary(max) NULL
)
PHP:
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
$cinfo = array(
"Database" => $database,
"UID" => $uid,
"PWD" => $pwd
);
$conn = sqlsrv_connect($server, $cinfo);
if( $conn === false )
{
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
# Update image using CONVERT()
$image = file_get_contents('image.jpg');
$sql = "UPDATE ImageTable SET [ImageData] = CONVERT(varbinary(max), ?) WHERE (yor_update_condition)";
$params = array(
array($image, SQLSRV_PARAM_IN)
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
# End
echo 'Image updated.'
?>

Use a function declared in a different file [PHP-HTML]

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.

Best practices when using PHP with Firebird or Interbase

The documentation for php-interbase is good - but not complete. In particular, there's no complete examples for working with Firebird. So how would you do it?
Basic guidelines.
Choosing between ibase_connect() vs ibase_pconnect() - the less time connections are active the less possible conflicts and the easier maintenance & backups can be performed. Unless connecting to the database is "expensive" in terms of processing time (you're performing large amounts of real-time reads/writes) use ibase_connect() as needed.
Always use explicit transactions. Always. It's simple - assume every call to ibase_prepare() or ibase_query() requires a transaction handle - never a "raw" connection handle.
Always follow a transaction with either a ibase_commit() or a ibase_rollback() as appropriate.
Basic template for a read operation:
// These would normally come from an include file...
$db_path = '/var/lib/firebird/2.5/data/MyDatabase.fdb';
$db_user = 'SYSDBA';
$db_pass = 'masterkey';
// use php error handling
try {
$dbh = ibase_connect( $db_path, $db_user, $db_pass );
// Failure to connect
if ( !$dbh ) {
throw new Exception( 'Failed to connect to database because: ' . ibase_errmsg(), ibase_errcode() );
}
$th = ibase_trans( $dbh, IBASE_READ+IBASE_COMMITTED+IBASE_REC_NO_VERSION);
if ( !$th ) {
throw new Exception( 'Unable to create new transaction because: ' . ibase_errmsg(), ibase_errcode() );
}
$qs = 'select FIELD1, FIELD2, from SOMETABLE order by FIELD1';
$qh = ibase_query( $th, $qs );
if ( !$qh ) {
throw new Exception( 'Unable to process query because: ' . ibase_errmsg(), ibase_errcode() );
}
$rows = array();
while ( $row = ibase_fetch_object( $qh ) ) {
$rows[] = $row->NODE;
}
// $rows[] now holds results. If there were any.
// Even though nothing was changed the transaction must be
// closed. Commit vs Rollback - question of style, but Commit
// is encouraged. And there shouldn't <gasp>used the S word</gasp>
// be an error for a read-only commit...
if ( !ibase_commit( $th ) ) {
throw new Exception( 'Unable to commit transaction because: ' . ibase_errmsg(), ibase_errcode() );
}
// Good form would dictate error traps for these next two...
// ...but these are the least likely to break...
// and my fingers are getting tired.
// Release PHP memory for the result set, and formally
// close the database connection.
ibase_free_result( $qh );
ibase_close( $dbh );
} catch ( Exception $e ) {
echo "Caught exception: $e\n";
}
// do whatever you need to do with rows[] here...

Can I convert mysql functions to PDO one at a time?

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.

Categories