I'm trying to use a PDO Wrapper Class and in general for proper security against SQL injections as good practice. Trying to learn the clean bare essentials for filling out a form to POST into MySQL.
So, at one point my form was inserting data into the MySQL table, but was doing multiple records on refresh after submit. Then I researched a cleaner way to write the processor but am now having trouble making it insert into the table. Not sure if maybe there is a discrepancy between the Processor and the "class.db.php" file?
I've searched a lot for "how-to's" having no success in a consistent answer. Trying to understand what I'm doing wrong, desiring an answer of best practice. Everything I've seen is all over the map.
Here's where I'm at:
For reference I started here first http://webdevelopingcat.com/php-mysql-tutorial-for-beginners-inserting-rows-with-pdo/
Then at top of the document I'm Including if you google, the https://code.google.com/p/php-pdo-wrapper-class/ project for a basis of class implementation.
<?php
include("class.db.php");
$version = "1.0.2";
$released = "December 9, 2010";
?>
Then a simple form within the body.
<?php
if ( empty( $_POST ) ){
?>
<form name='registration' action='success.php' method='POST'/>
<label for 'FName'>First Name: </label>
<input type="text" name="FName" />
<label for 'LName'>Last Name: </label>
<input type="text" name="LName" />
<label for 'Age'>Age: </label>
<input type="number" name="Age" />
<label for 'Gender'>Gender: </label>
<input type="text" name="Gender" />
<button type="submit">Submit</button>
</form>
Finally the form processor also within the body.
<?php
} else {
//process the form here
//
// Connect to database
$db = new db("mysql:host=localhost;dbname=pdodb", "root", "root");
$form = $_POST;
$first = $form[ 'FName' ];
$last = $form[ 'LName' ];
$myage = $form[ 'Age' ];
$gen = $form[ 'Gender' ];
$sql = "INSERT INTO mytable ( FName, LName, Age, Gender ) VALUES ( :first, :last, :myage, :gen )";
$query = $db->prepare( $sql );
$query->execute( array( ':first'=>$first, ':last'=>$last, ':myage'=>$myage, ':gen'=>$gen ) );
}
?>
The MANUAL way works. Referenced culttt.com post about: prevent-php-sql-injection-with-pdo-prepared-statements
// Create array of data to insert
$insert = array(
"FName" => "John",
"LName" => "Doe",
"Age" => 26,
"Gender" => "male"
);
// Insert the array into the table
$db->insert("mytable", $insert);
Your form is posting to success.php, so make sure that the insert code is in the success.php file:
<?php
// Get POST data
$first = (!empty($_POST['FName']) ? $_POST['FName'] : '');
$last = (!empty($_POST['LName']) ? $_POST['LName'] : '');
$myage = (!empty($_POST['Age']) ? $_POST['Age'] : '');
$gen = (!empty($_POST['Gender']) ? $_POST['Gender'] : 0);
try {
// Connect to db
$db = new db('mysql:dbname=pdodb;host=localhost', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set SQL
$sql = 'INSERT INTO mytable (FName, LName, Age, Gender) VALUES (:first, :last, :myage, :gen)';
// Prepare query
$query = $db->prepare($sql);
// Execute query
$query->execute(array(':first' => $first, ':last' => $last, ':myage' => $myage, ':gen' => $gen));
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
Thanks,
Andrew
<?php
// Get POST data
$first = (!empty($_POST['FName']) ? $_POST['FName'] : '');
$last = (!empty($_POST['LName']) ? $_POST['LName'] : '');
$myage = (!empty($_POST['Age']) ? $_POST['Age'] : '');
$gen = (!empty($_POST['Gender']) ? $_POST['Gender'] : 0);
try {
// Connect to db
$db = new PDO('mysql:dbname=pdodb;host=localhost', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Set SQL
$sql = 'INSERT INTO mytable (FName, LName, Age, Gender) VALUES (:first, :last, :myage, :gen)';
// Prepare query
$query = $db->prepare($sql);
// Execute query
$query->execute(array(':first' => $first, ':last' => $last, ':myage' => $myage, ':gen' => $gen));
$db= null;
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
$db= null;
}
Related
I want to save the data with php. The program does not return an error. But to the database does not record.
DOSYA ADI:signup.php
MY CODES:
<form action="islem.php" method="post">
Ad:<input type="text" name="bilgilerim_ad" placeholder="giriniz">
Soyad:<input type="text" name="bilgilerim_soyad" placeholder="giriniz">
Mail:<input type="text" name="bilgilerim_mail"placeholder="giriniz">
Yaş:<input type="text" name="bilgilerim_yas" placeholder="giriniz">
<button name="insertislemi" type="submit">Kayıt</button>
</form>
DOSYA ADI:config.php
MY CODES
<?php
include 'baglan.php';
if(isset($_POST['insertislemi'])){
$query = $db->prepare("INSERT INTO uyeler SET
bilgilerim_ad =: bilgilerim_ad,
bilgilerim_soyad =: bilgilerim_soyad,
bilgilerim_mail =: bilgilerim_mail,
bilgilerim_yas =: bilgilerim_yas,
");
$insert = $query->execute(array(
"bilgilerim_ad" => $_POST['bilgilerim_ad'],
"bilgilerim_soyad" => $_POST['bilgilerim_soyad'],
"bilgilerim_mail" => $_POST['bilgilerim_mail'],
"bilgilerim_yas" => $_POST['bilgilerim_yas'],
));
if ( $insert ){
$last_id = $db->lastInsertId();
print "insert işlemi başarılı!";
}
}
?>
MY CODES
CONNECTION FILE
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=test", "root", "");
//echo "giriş";
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
You first write bilgilerim_ad =: bilgilerim_ad, ... in your insert query, then "bilgilerim_ad" => $_POST['bilgilerim_ad'],.
There's a misplaced space, the datas are bound to bilgilerim_ad but you declared : bilgilerim_ad.
Replace your insert query by :
$query = $db->prepare("INSERT INTO uyeler SET
bilgilerim_ad = :bilgilerim_ad,
bilgilerim_soyad = :bilgilerim_soyad,
bilgilerim_mail = :bilgilerim_mail,
bilgilerim_yas = :bilgilerim_yas");
And bind your datas this way :
$insert = $query->execute(array(
":bilgilerim_ad" => $_POST['bilgilerim_ad'],
":bilgilerim_soyad" => $_POST['bilgilerim_soyad'],
":bilgilerim_mail" => $_POST['bilgilerim_mail'],
":bilgilerim_yas" => $_POST['bilgilerim_yas']));
This is out of topic, but in your php files where you are using only php code (the one that insert and the one that manage DB connection in example) do not close php tag ?>. This can send unwanted characters to http header
I'm making a register/login in php. Right now I'm trying to register via an html formulaire, having fill the input, I'm receiving this in the terminal :
[Tue Nov 28 22:57:30 2017] ::1:59017 [200]: /
But nothing goes in my database. I'm going crazy, I don't understand what's wrong :
my dbconfig :
<?php
$config = [
"host" => "host",
"dbname"=>"dbname"
"user" => "dbuser",
"password" => "dbpassword",
];
?>
my dbconnexion :
<?php
require_once(realpath(dirname(__FILE__))."/../config/dbconfig.php");
try {
$pdo = new PDO('mysql:host='.$config["host"].';dbname='.$config["dbname"], $config["user"], $config["password"]);
} catch (PDOException $e) {
print "Erreur !: " . $e->getMessage() . "<br/>";
}
And finally my index.php :
<?php
echo "<h1> BulletProof </h1>";
require './utils/dbconnexion.php';
//session_start();
?>
<form method="POST">
<label>Pseudo: <input type="text" name="nickname_register"/></label><br/>
<label>Mot de passe: <input type="password" name="password_register"/></label><br/>
<input type="submit" value="M'inscrire"/>
</form>
<?php
if(isset($_POST['nickname_register']) && !empty($_POST['nickname_register']) && isset($_POST['password_register']) && !empty($_POST['password_register'])){
$pseudo_register = htmlspecialchars($_POST['nickname_register']);
$password_register = htmlspecialchars($_POST['password_register']);
$password_hash = password_hash($password_register, PASSWORD_DEFAULT);
$q = $pdo->prepare('INSERT user (nickname, password) VALUES (:nickname, :password');
$q->bindParam(':nickname', $nickname_register, PDO::PARAM_STR);
$q->bindParam(':password', $password_hash, PDO::PARAM_STR);
$register = $q->execute();
}
?>
Can someone please tell me what I'm doing wrong ?
I've looked into my syntaxe, my sql request, my info to connect the database, but I don't see anything wrong
You forgot the INSERT statement syntax which should be INSERT INTO :
$q = $pdo->prepare('INSERT INTO user (nickname, password) VALUES (:nickname, :password)');
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I can't insert the text from textarea when the text has apostrophe please sir's how to fix it.
this my whole code. I try mysqli_real_escape_string but it gives a error.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "srdatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
$speakerid = $_SESSION['speakerid'];
$speaker_info = "SELECT * FROM speakers WHERE id=$speakerid";
$si_result = mysqli_query($conn, $speaker_info);
$array = mysqli_fetch_array($si_result);
$dbfullname = $array['speaker_fullname'];
$dbimage = $array['speaker_image'];
$dbspecialization = $array['speaker_specialization'];
$dbdescription = $array['speaker_description'];
$dbpaymentcost = $array['speaker_paymentcost'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<form action="updateSpeaker.php" method="post" enctype="multipart/form-data">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?php echo htmlspecialchars($dbdescription);?></textarea>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
<?php
if(isset($_POST['update']))
{
$newdescription = $_POST["description"];
$finaldescription = $mysqli_real_escape_string($conn, $newdescription);
$update_data = "UPDATE speakers SET speaker_fullname = '".$_POST["fullname"]."', speaker_description = '$finaldescription', speaker_specialization = '".$_POST["specialization"]."', speaker_paymentcost = '".$_POST["paymentcost"]."' WHERE id=$speakerid";
mysqli_query($conn, $update_data);
}
?>
</body>
</html>
Prepared statement:
$update_data = "UPDATE speakers SET speaker_fullname=?, speaker_description=?, speaker_specialization=?, speaker_paymentcost=? WHERE id=?";
$stmt = mysqli_prepare($conn, $update_data);
mysqli_stmt_bind_param($stmt, 'ssssd', $_POST["fullname"], $finaldescription, $_POST["specialization"], $_POST["paymentcost"], $speakerid);
Your current code is also mixing OOP and procedural based functions, so it will not work even once you have fixed the original issue with quoting user input.
I have converted your code into PDO (untested), which should point you in the right direction. Hope it helps.
<?php
session_start();
// config holder
$config = [
'db' => [
'host' => 'localhost',
'user' => 'root (DONT USE ROOT)',
'pass' => '',
'name' => 'srdatabase',
]
];
// connect to database
try {
$db = new PDO(
"mysql:host=" . $config['db']['host'] .";dbname=". $config['db']['name'],
$config['db']['user'],
$config['db']['pass'],
array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
} catch (PDOException $e) {
exit('Could not connect to database.');
}
// check id, though should be getting this from a $_GET
if (empty($_SESSION['speakerid']) || !is_numeric($_SESSION['speakerid'])) {
exit('Invalid speaker id');
}
// handle post
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = [];
// check or set inbound variables
$id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
$description = isset($_POST['description']) ? $_POST['description'] : null;
// you could set errors here if there empty, but lets continue
/*
if (empty($description)) {
$errors['description'] = 'Description is a required field.';
}
*/
if (
empty($errors) && // check for no errors
!empty($id) && // not required if you checked above, check id is not empty
!empty($description) // not required if you checked above, check description is not empty
) {
// prepare query for update, only want to update description
try {
$stmt = $db->prepare('
UPDATE speakers
SET speaker_description = :description
WHERE id = :id
');
// bind inbound variables to the query, then execute
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
} catch (PDOException $e) {
$errors['query'] = 'Error updating database: '.$e->getMessage();
}
}
}
// select current row based upon the id
$stmt = $db->prepare('SELECT * FROM speakers WHERE id = :id LIMIT 1');
$stmt->bindParam(':id', $_SESSION['speakerid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();
/* would contain
$result['speaker_fullname'];
$result['speaker_image'];
$result['speaker_specialization'];
$result['speaker_description'];
$result['speaker_paymentcost'];
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>Update Speaker</title>
</head>
<body>
<?php if (!empty($errors['query'])): ?>
<?= $errors['query'] ?>
<?php endif ?>
<form action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="id" value="<?= $_SESSION['speakerid'] ?>">
<textarea name="description" class="inputbox" cols="60" rows="5" autofocus required="required" maxlength="2000" style="resize:none;" placeholder="Description"><?= htmlentities($result['speaker_description']) ?></textarea>
<?php if (!empty($errors['description'])): ?>
<span style="color:red"><?= $errors['description'] ?></span>
<?php endif ?>
<br>
<input name="update" id="buttonsubmit" type="submit" value="Update">
</form>
</body>
</html>
I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">
i need your help. today i saw that if i put '(apostrophe) in some words then this text will not send to database. I tride to delete htmlentites or htmlspecialchars but not helped. please help me to fix this problem. thanks.
hier is profile.php
<?php
if(logged_in() === true){
if(empty($_POST['status']) === false && empty($_POST['user_status']) === false){
$status_data = array(
'body' => $_POST['status'],
'added_by' =>$user_data['username'],
'date_added' => date('Y-m-d H:i:s'),
'user_posted_to' => $_GET['username'],
'user_id' => $user_data['user_id']
);
update_status($id, $status_data, $user_id);
}
?>
<form class="forma" action="<? echo $username; ?>" method="post" accept-charset="utf8">
<div class="field">
<label for="Status" style="color: #7f7f7f; font-family: Cambria, Hoefler Text, Liberation Serif, Times, Times New Roman, serif;"></label>
<textarea rows="4" cols="50" name="status" placeholder="say something" id="status_area" charset="UTF-8" style=".value:black;"></textarea>
<div class='fild_bottom'>
<input name="user_status" type="submit" value="Post" id="button">
</div>
</div>
</form>
Here is function.php:
function update_status($id, $status_data, $user_id){
$query = #mysql_query('set character_set_results = "utf8"');
$user_id = mysql_query("SELECT * FROM users WHERE user_id = $user_id");
array_walk($status_data, 'array_sanitize');
$fields = '`' . implode('`,`', array_keys($status_data)) . '`';
$bank ='\'' . implode('\', \'', $status_data) . '\'';
mysql_query("INSERT INTO `status` ($fields) VALUES ($bank)");
}
function array_sanitize($item){
$item = htmlentities(strip_tags(mysql_real_escape_string($item)));
}
function sanitize($data){
return htmlspecialchars(strip_tags(mysql_real_escape_string($data)));
}
Please change your code to PDO. For an example, I'm refering to this SO Question
Change your function update_status to this (it's implied you've already made an db connection (object in $db)):
/* $user_id is unused, you should think about removing it */
function update_status($id, $status_data, $user_id) {
global $db;
$link = $db->prepare("INSERT INTO `status` (`body`, `added_by`, `date_added`, `user_posted_to`, `user_id`) VALUES (?, ?, ?, ?, ?)");
$link->bindvalue(1, $status_data['body']);
$link->bindvalue(2, $status_data['added_by']);
$link->bindvalue(3, $status_data['date_added']);
$link->bindvalue(4, $status_data['user_posted_to']);
$link->bindvalue(5, $status_data['user_id']);
$link->execute();
}
And remove the functions array_sanitize() and sanitize(), you won't need them anymore (Thanks to PDO and Prepared Statements). Also there is no need to use array_keys on the $status_data array, if the keys are always the same and known.
I don't know why you're selecting the user_id again in this function, since you're already getting it in $status_data.
edit: Throw this in a central file (you can either set the variables before try { or replace them with the correct values):
try {
$db = new PDO("mysql:host=".$host.";dbname=".$db.";charset=utf8", $user, $password);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //Stops emulating Prepared Statements
} catch(PDOException $e) {
die("Unable to connect. Error: ".$e->getMessage());
}