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());
}
Related
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>
EDIT: Seems to be something with the database. We cant figure out what it is.
Im having a problem with storing data thats been put into the forms. I tested the query in MS SQL (we have to use that for school) but it doesnt seem to work once i put in my variables. So im guessing the problem comes from the variables. However im not sure about that because when i echo the $_POST variables it outputs strings like i want it to. But when i put it in the query it just wont store rit in my database. Would be great if someone could help me out with this.
HTML code:
<form action="registerSystem.php" method="post">
Email:
<input type="email" name="emailAdres" required> <br>
Naam:
<input type="text" name="naamGebruiker" required> <br>
Wachtwoord:
<input type="password" name="wachtwoordGebruiker" required> <br>
Herhaal wachtwoord:
<input type="password" name="bevestigWachtwoord" required> <br>
<input type="submit" value="Registreer">
</form>
Php code:
require "connect.php";
session_start();
GLOBAL $conn;
function createAccount(){
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) "
."VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$conn->query($query);
}
if($_SERVER['REQUEST_METHOD'] === 'POST'){
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("location: loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}?>
I have found where the problem is on your function.
The problem is here : VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
that null after :subscription_start is the problem, rather put a place holder in place then have a string that you will assign it value to null. then your query should work.
I'm not sure what datatype is subscription_end but I guess it should be date. and also use try catch block so that you can see when you have errors in your sql query. Also don't rush to reload the next page after running your query atleast but some delay on your header() so that you can print success message and see if its displaying then load next page
So this is how I updated your function.
<?php
require 'connect.php';
session_start();
GLOBAL $conn;
function createAccount()
{
$email = $_POST['emailAdres'];
$username = $_POST['naamGebruiker'];
$wachtwoord = $_POST['wachtwoordGebruiker'];
GLOBAL $conn;
$hashed_pass = md5($wachtwoord);
$paypal = $email;
$subscription_start = date("Y:m:d");
$land = 'Nederland';
$enddate = 'null';
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name) " . "VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, :enddate, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->bindParam(':enddate', $enddate);
if ($query->execute()) {
echo "Done";
}
}
catch (PDOException $e) {
echo "error". $e->getMessage();
}
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//password check
if ($_POST['wachtwoordGebruiker'] == $_POST['bevestigWachtwoord']) {
createAccount();
header("refresh:5;url=loginSystem.php");
} else {
echo "De opgegeven wachtwoorden komen niet overeen!";
}
}
?>
Hope this helps.
NB: Don't use md5(); to encrypt your passwords its no longer safe,
rather use php functions password_hash() and password_verify()
they are available on php.net for you to read and understand them.
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
What I've changed here is $conn->query($query); to $query->execute(). Because you're working with prepared statements, you need to call execute method of the object instance of prepared statement $query.
$conn->query($sql) is commonly used when only retrieving results with SELECT query which doesn't contain filtering conditions that receive data from user inputs.
For your information, as a best practice, wrap up the code with try catch blocks which helps you handle the errors.
try {
$query = $conn->prepare("INSERT INTO Customer (customer_mail_adress, name, paypal_account, subscription_start, subscription_end, password, country_name)"
." VALUES (:customer_mail_adres, :naam, :paypal, :subscription_start, null, :password, :country_name)");
$query->bindParam(':customer_mail_adres', $email);
$query->bindParam(':naam', $username);
$query->bindParam(':paypal', $paypal);
$query->bindParam(':subscription_start', $subscription_start);
$query->bindParam(':password', $hashed_pass);
$query->bindParam(':country_name', $land);
$query->execute();
} catch (PDOException $ex) {
echo $ex->getMessage(); // or die($ex->getMessage());
}
Before using try catch blocks, set the PDO's error reporting to exception:
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Set this attribute as soon as you created the PDO object instance.
You can also set this attribute during the object instantiation through constructor like:
$conn = new PDO('mysql:host=localhost;dbname=demo', 'root', 'password', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
Hope it helps!
I was wondering if you could help me with a problem when submitting a form to POST values and using a PDO Insert function to enter values into database. Once someone can help me find the issue I will be able to use code over again in form areas. I have checked my $conn PDO statement and it is connected correctly to database just I can not insert the data from form.
My coding layout:
Form located in cust_form.php, names of form fields are as in database with the exception of an autoID generated upon insertion.
Class.php is used to take POST values and to send to Insert function located in db.php.
db.php
<?php
//dbdt database class
if(!class_exists('dbdt')){
class dbdt {
//Connect and select database
function connect() {
try {
require_once('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends', $DB_USER, $DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Connect to above
function __construct() {
$this->connect();
}
//Insert data into database
function insert($conn, $table, $fields, $values) {
try{
$fields = implode(", ", $fields);
$values = implode(", ", $values);
$insert = "INSERT INTO $table (autoID, $fields) VALUES ('', $values)";
$query = $handler->prepare($insert);
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
}
}
$dbdt = new dbdt;
?>
class.php
<?php
if(!class_exists('cust_form')){
class cust_form {
/*
CUSTOMER FORM = cust_form.php
*/
function cust_upd_cre_del(){
if ( isset( $_POST['cust_upd'] ) ) {
$int_custID=$_POST['int_custID'];
$cust_company=$_POST['cust_company'];
$cust_address=$_POST['cust_address'];
$cust_postcode=$_POST['cust_postcode'];
$cust_contact_1=$_POST['cust_contact_1'];
$cust_contact_2=$_POST['cust_contact_2'];
$cust_tel=$_POST['cust_tel'];
$cust_mob=$_POST['cust_mob'];
$cust_DDI=$_POST['cust_DDI'];
$cust_email=$_POST['cust_email'];
$cust_notes=$_POST['cust_notes'];
require_once('db.php');
$table = 'customers';
$fields = array(
'int_custID',
'cust_company',
'cust_address',
'cust_postcode',
'cust_contact_1',
'cust_contact_2',
'cust_tel',
'cust_mob',
'cust_DDI',
'cust_email',
'cust_notes'
);
$values = array (
'int_custID' => $int_custID,
'cust_company' => $cust_company,
'cust_address' => $cust_address,
'cust_postcode' => $cust_postcode,
'cust_contact_1' => $cust_contact_1,
'cust_contact_2' => $cust_contact_2,
'cust_tel' => $cust_tel,
'cust_mob' => $cust_mob,
'cust_DDI' => $cust_DDI,
'cust_email' => $cust_email,
'cust_notes' => $cust_notes
);
$insert = $dbdt->insert($conn, $table, $fields, $values);
if ( $insert == TRUE ) {
}
} else {
die('Your form was not submitted.');
}
}
}
}
$cust_form = new cust_form;
?>
cust_form.php
<!doctype html>
<?php
require_once('load.php');
?>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Form</title>
</head>
<body>
<form action="" method="POST" name="cust_details_form" id="cust_details_form">
<label>Account No:</label>
<input type="text" name="int_custID" id="int_custID" />
<label>Company:</label>
<input type="text" name="cust_company" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 name="cust_address" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" name="cust_postcode" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" name="cust_contact_1" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" name="cust_contact_2" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" name="cust_tel" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" name="cust_mob" id="cust_mob"/>
<label>DDI:</label>
<input type="text" name="cust_DDI" id="cust_DDI"/>
<label>Email:</label>
<input type="email" name="cust_email" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 name="cust_notes" id="cust_notes"></textarea>
<input type="submit" name="cust_upd" id="cust_upd" value="Update">
<input type="submit" name="cust_del" id="cust_del" value="Delete">
</form>
</body>
</html>
load.php contains require_once db.php, class.php & config.php (contains username and password). This file is okay.
Thanks for any help you may be able to give!
EDITTED
Thanks for all your help! Here is the working code for anyone who needs it!
function ins_upd($table, $values) {
try{
include('config.php');
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', $DB_USER, $DB_PASS);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip $_POST array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
You don't need to send "fields" parameters because if that array is in a different order than "values" your code won't work. Use the array keys from "values":
//Insert data into database
function insert($conn, $table, $values) {
try {
$keys = array_keys($values);
$fields = implode(", ", $keys);
$values = ":" . implode(", :", $keys);
$insert = "INSERT INTO $table ($fields) VALUES ($values)";
$query = $handler->prepare($insert);
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
Hope it helps. I couldn't test it without complete code.
PS: Avoid using prepare to execute SQL statements without using bindParam because you must to quote strings but not integers or floating point numbers.
I am trying to write some information into an SQL database from my website using PHP. I can access the database to login, however I can not write anything to it from my website. Also, I can not view any connection errors.
Form Page:
<?php
$dbh = new PDO('mysql:host='.$hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
?>
<div id="imagel">
<img class="imagel" src="../images/logos/logo2.jpg" width="300" height="300" alt="studio table" />
</div>
<div id="textr">
<form name="tableofevents" method="post" action="adminhome.php">
Name of Event(Maximum of 83 characters): <input type="text" name="noe"/>
<br>
Event Description (Maximum of 288 characters): <input type="text" name="eventdescription"/>
<br>
Date of Event: <input type="text" name="date"/>
<br>
Ticket Price: <input type="text" name="price"/>
<br>
<input type="submit" name="submit" text="submit"/>
</form>
Processing Page:
<?php
$hostname = 'localhost';
$user='******';
$pass='***********';
$dbname='sth420';
$handler = new PDO('mysql:host='.$hostname.';dbname='.$dbname,$user,$pass);
$dbh = mysql_connect ($hostname.';dbname='.$dbname, $user, $pass);
if (!$dbh) { die('Could not connect: ' . mysql_error()); }
else echo 'connected';echo '<br>';
if(isset($_COOKIE['username']))
{
$username=$_COOKIE['username'];
$password=$_COOKIE['password'];
$sql='SELECT * FROM Users WHERE ID=:id';
$results = $handler->prepare($sql);
$results->execute([':id' => $username]);
$row = $results->fetch();
if($row!=null)
{
$pword = $row['Password'];
if($pword == $password)
{
if(isset($_POST['submit']))
{
$noe=$_POST['noe'];
$ed=$_POST['eventdescription'];
$date=$_POST['date'];
$price=$_POST['price'];
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
mysql_error()
$results = $handler->prepare($sql);
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
$handler = null;
header('Location: events.html');
}
}
}
}
if (!mysql_query($sql,$dbh))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($dbh);
require_once('adminhome.html');
?>
You are mixing PDO and mysql_connect(). That is invalid, as they are incompatible APIs. Remove all references to mysql_*() and stick only with your PDO statements. You have basically duplicated every PDO statement with an incorrect call to mysql_query() but you should have none of mysql_connect(), mysql_query(), mysql_error(), mysql_fetch_*().
Refer to the manual on PDO prepared statements to see the many examples.
I see a mismatch between column counts here. You list 4 columns, but the VALUES () list contains 5:
// Prepared statemetn looks ok...
$sql='INSERT INTO ismievents ( title, evtdesc, dandt, price ) VALUES(0, :noe, :eventdescription, :date, :price)';
// But this is meaningless here...
mysql_error()
I note also that you are using PHP 5.4 array literals like:
$results->execute([':noe' => $noe, ':eventdescription' => $ed, ':date' => $date, ':price' => $price]);
Hopefully you are actually running this code in PHP 5.4.
Really, you need to take this code back to the drawing board to purge it of the incompatibilities between PDO and mysql_*(). After that, you will be able to narrow down other problems with it.
A final note here, it is really inadvisable to store a password in $_COOKIE. On a successful login, instead store a logged in state in $_SESSION.
I'm trying to use the code below for a comment system. It doesn't work. The info I'm trying to insert into the MySQL table "comment" isn't getting put there. Any idea(s) why it is not working?
Thanks in advance,
John
On comments.php:
echo '<form action="http://www...com/sandbox/comments/comments2.php" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
On comments2.php:
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
mysql_query("INSERT INTO comment VALUES (NULL, '$uid', '$subid', '$comment', NULL, NULL)");
try
$query = sprintf("INSERT INTO comment VALUES (NULL, '%s', '%s', '%s', NULL, NULL)", $uid, $subid, $comment);
mysql_query($query);
If mysql_query() fails it returns false and mysql_error() can tell you why.
Also take a look at http://docs.php.net/security.database.sql-injection and either use mysql_real_escape_string() or prepared statements.
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
$rc=mysql_query($query, $mysql);
if ( !$rc ) {
die( htmlspecialchars(mysql_error()) );
}
Try this self-contained example (only an example, don't code it this way ;-))
<?php
session_start();
if ( !isset($_SESSION['loginid']) ) {
login();
}
else if ( !isset($_POST['comment']) ) {
showForm();
}
else {
saveComment();
}
function saveComment() {
if ( !isset($_POST['comment'], $_POST['uid'], $_POST['submissionid']) ) {
echo '<pre>Debug: Something is missing. _POST=',
htmlspecialchars( print_r($_POST, 1) ),
'</pre>';
die;
}
// insert correct values here:
$mysql = mysql_connect('localhost', 'localonly', 'localonly') or die(mysql_error());
mysql_select_db('test', $mysql) or die(mysql_error());
$comment = mysql_real_escape_string($_POST['comment'], $mysql);
$uid = mysql_real_escape_string($_POST['uid'], $mysql);
$subid = mysql_real_escape_string($_POST['submissionid'], $mysql);
$query = "
INSERT INTO
comment
VALUES
(NULL, '$uid', '$subid', '$comment', NULL, NULL)
";
echo '<pre>Debug query=', htmlspecialchars($query), '</pre>';
//$rc=mysql_query($query, $mysql);
//if ( !$rc ) {
//die( htmlspecialchars(mysql_error()) );
//}
}
function login() {
$_SESSION['loginid'] = rand(1, 100);
echo 'Your new loginid is ', $_SESSION['loginid'],'<br />
Continue
';
}
function showForm() {
$submissionid = rand(1000, 9999);
echo '<div>submissionid=', $submissionid, '</div>';
echo '<div>loginid=', $_SESSION['loginid'], '</div>';
echo '<form action="?" method="post">
<input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
<input type="hidden" value="'.$submissionid.'" name="submissionid">
<label class="addacomment" for="title">Add a comment:</label>
<input class="commentsubfield" name="comment" type="title" id="comment" maxlength="1000">
<div class="commentsubbutton"><input name="submit" type="submit" value="Submit"></div>
</form>
';
}
if this "works" compare it to your real application and find the (essential) differences.
Valid return values from yourform
Does
$comment = $_POST['comment'];
$uid = $_POST['uid'];
$subid = $_POST['submissionid'];
contain valid data?
SQL query valid
http://www.w3schools.com/sql/sql_insert.asp
What does mysql_query return
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
what mysql_error do you get for your query.
Use PDO instead of mysql_query()
I would advise you to have a look at PDO which does a lot of heavy lifting for you. It for example makes sure that your SQL query is safe because even if the comments was added to your database it could(would) not be safe at all.
PHP security
You should always validate your users input to prevent SQL injection. Luckily when using PDO(using prepared statements which will also give you a speed boost)right this will be done for you behind the seens. Still I would advise you to read these quick security tips from PHP creator to secure your site.
Hopefully this tips will help you in any way.
You need the field names for any INSERT statement. As I don't know the exact ones for your table, I'll make some guesses.
mysql_query("INSERT INTO comment(uid,subid,comment) VALUES($uid, $subid, $comment)");