This question already has answers here:
How do I display a MySQL error in PHP for a long query that depends on the user input? [duplicate]
(6 answers)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
I'm trying to insert values in table it is saying error please tell me where i'm wrong here is my code
its said please try again
<?php
include_once('dbconnect.php');
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$phone = $_POST['phone'];
$cash = $_POST['cash'];
if(mysql_query("INSERT INTO tbl2 VALUES('',$name','$phone','$cash','date('l jS \of F Y h:i:s A'))"))
echo "Successful Insertion!";
else
echo "Please try again";
}
$res = mysql_query("SELECT * FROM tbl2");
?>
<form action="" method="POST">
<input type="text" name="name"/><br />
<input type="text" name="phone"/><br />
<input type="text" name="cash"/><br />
<input type="submit" name="submit" value=" Enter "/>
</form>
<h1>List of companies ..</h1>
<?php
while( $row = mysql_fetch_array($res) )
echo "$row[id].$row[Name]
<a href='edit.php?edit=$row[id]'>edit</a><br />";
?>
will you guide me i thought the problem is in date date
Two things I can think of top my head;
mysql_ has been deprecated, thus the else kicks in.
Your syntax maybe wrong for mysql_query?
Nonetheless, start over and start over with code that is functional and up-to-date...
Given that your connection is working properly update it to a new mysqli syntax, it's very simple and much more elegant:
$connect = new mysqli( 'localhost', 'USERNAME', 'PASSWORD', 'DATABASE' );
// check for an error
if ($this->_connection->connect_error)
{
trigger_error("Connection Error: " . $this->_connection->connect_error(), E_USER_ERROR);
}
Now that you are connected walk-through a new process for your code.
Start by checking like you currently are for a submit $_POST so that you can start running the script:
if ( isset( $_POST['submit'] ) )
{
// Encode the URL when creating the variables
$name = htmlentities( $_POST['name'] );
$phone = htmlentities( $_POST['phone'] );
$cash = htmlentities( $_POST['cash'] );
$date = date( 'l jS \of F Y h:i:s A' );
// create sql
// DO NOT INSERT VALUES STRAIGHT INTO YOUR QUERY
$sql = "INSERT INTO tbl2 ( name, phone, cash, date ) VALUES ( ?, ?, ?, ? )";
Note: before continuing, let me explain that you should never insert content into your query because that would throw raw user input in the mist of your code. Now, most users will never try anything fishy. But anyone could easily throw a few SQL commands inside of your inputs and DELETE, SELECT, and UPDATE your database content and cause numerous problems.
Here is some reference: https://en.wikipedia.org/wiki/SQL_injection
To work around that problem, use prepared statements. You can read all about it on PHP manual; and also see some real-life examples.
// prepare query
// USE PREPARED STATEMENTS
if ($stmt = $connect->prepare( $sql ))
{
// bind the params
$stmt->bind_param('ssss', $name, $phone, $cash, $date);
// execute the query
$stmt->execute();
// check for errors
if ($stmt->errno)
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: ' . $stmt->error
);
}
// make sure at least 1 or more rows were affected
if ($stmt->affected_rows > 0)
{
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' rows were inserted.' // value should be 1
);
}
else
{
// if not, send warning to user
$message = array(
'is_error' => 'warning',
'message' => 'Warning: ' . $stmt->affected_rows . ' rows were updated.'
);
}
// close your connection
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'QUERY: error. Try again.'
);
exit;
}
}
else
{
$message = array(
'is_error' => 'warning',
'message' => 'There was no submission attempt. Try again.'
);
exit;
}
Notice in the code is broken down into parts where you can catch multiple errors, and it's important for debugging; it will allow you to know exactly where the code went wrong, and localize your problem to a single section of it.
Related
I am hoping that I've just been looking at and debugging this code too long (days now!) and I'm just not seeing the problem.
I'm obviously trying to add an entry in to a MySQL database via my PHP code. To use the classic phrase "this code has always worked before and now it doesn't and I didn't change anything" ;-)
My code, with my current debugging traps, looks like this:
// Prepare SQL Insert
$strInsert = "INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM) " .
"VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)";
$DBInsertHorse = $DB->prepare($strInsert);
// Insert new Horse
$iCtr = 0;
do {
try {
$DBInsertHorse->execute(array(
'HORSENAME' => strtoupper($HorseName),
'HORSEYOB' => $YOB,
'HORSECOB' => $COB,
'HORSESEX' => strtoupper($HorseSex),
'HORSEYOD' => $YOD,
'HORSEDEAD' => $bDead,
'FAM' => $FAM,
'FDM' => $FDM)
);
}
catch (Exception $error) {
die($error->getMessage());
}
} while ($find($DB, strtoupper($HorseName), $YOB, $COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);
// Could not insert
if ($iCtr == MAX_INSERT_ATTEMPTS) {
// DEBUG HORSE IMPORT
if (is_null($HorseName))
$HorseName = 'NULL';
if (is_null($YOB))
$YOB = -2;
if (is_null($COB))
$COB = 'NULL';
if (is_null($HorseSex))
$HorseSex = 'NULL';
if (is_null($YOD))
$YOD = -2;
if (is_null($bDead) || !$bDead)
$Dead = -2;
if (is_null($FAM))
$FAM = 'NULL';
if (is_null($FDM))
$FDM = 'NULL';
error_log('INSERT ERROR: Horse: \'' . strtoupper($HorseName) . '\' - YOB: ' . $YOB . ' - COB: \'' . $COB . '\' - SEX: \'' . strtoupper($HorseSex) . '\' - YOD: ' . $YOD . ' - Dead: ' . $bDead . ' - FAM: ' . $FAM . ' - FDM: ' . $FDM);
return(false);
}
If I go my favourite SQL editor (SQLPro for MySQL) and I enter in the insert manually it works fine:
INSERT INTO Horses (HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES ('HorseName', 2001, null, 'M', null, false, null, null)
For info:
The find() function used is my own and wraps a "SELECT FROM ..." query and works fine. If I do a SELECT from the Horses table in the database afterwards the Horse was never added.
MAX_INSERT_ATTEMPTS is my constant and the value is currently set at 5.
I'm working with MaMP PRO and I've looked in my PHP error log, where only the message I sent there appears and no other errors and in my MySQL error log, where no error message appears.
I can't figure out where to look next and I'm hoping whatever my stupid error might be is going to jump out at someone else looking at my code.
Thanks for looking and for any ideas, suggestions or corrections you may have.
UPDATED CODE WITH DEBUGGING
do {
try {
$DBInsertHorse->bindValue(':HORSENAME', strtoupper($this->Name));
$DBInsertHorse->bindValue(':HORSEYOB', $this->YOB);
$DBInsertHorse->bindValue(':HORSECOB', $this->COB);
$DBInsertHorse->bindValue(':HORSESEX', strtoupper($this->Sex));
$DBInsertHorse->bindValue(':HORSEYOD', $this->YOD);
$DBInsertHorse->bindValue(':HORSEDEAD', (int)$this->Dead);
$DBInsertHorse->bindValue(':FAM', $this->FAM);
$DBInsertHorse->bindValue(':FDM', $this->FDM);
$DBInsertHorse->execute();
}
catch (PDOException $e) {
error_log('SQL INSERT ERROR: ' . $e->getMessage());
}
} while($this->find($DB, strtoupper($this->Name), $this->YOB, $this->COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);
As #BillKarwin mentioned I was missing a proper call to
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Once that was in place I was able to see where the error was. This error apparently has appeared since my upgrade to PHP 7.2.10.
I also changed my call to array to a list of calls to bindValue... I may go back to array() but that's not important. ;-)
The PHP code did not like my passing "false" to a tinyint field. I had to type the variable with a call to (int)varname and everything works fine now.
(int)$this->Dead;
THANK YOU ALL!
Check this, it's tested and it works. Also check do while statement.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)");
$stmt->bindParam(':HORSENAME',$HorseName);
$stmt->bindParam(':HORSEYOB', $YOB);
$stmt->bindParam(':HORSECOB', $COB);
$stmt->bindParam(':HORSESEX', $HorseSex);
$stmt->bindParam(':HORSEYOD', $YOD);
$stmt->bindParam(':HORSEDEAD', $bDead);
$stmt->bindParam(':FAM', $FAM);
$stmt->bindParam(':FDM', $FDM);
// insert a row
$HorseName = strtoupper($HorseName);
$YOB = "John";
$COB = "John";
$HorseSex = strtoupper($HorseSex);
$YOD = "John";
$bDead = "John";
$FAM = "John";
$FDM = "John";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
I have a 3 parameters which should append new/update old entries to a custom mysql table. However, I cannot figure out WHY when I press the submit button ... nothing happens (nor do I get any errors). I am at a loss for what to do. I have asked this question before and have modified my code a bit based on other tutorials thinking that was my issue... no luck :(
I understand that there are concerns for mysql injections - presently I'd just like to see it work and if you have suggestions for mitigating injections I am all ears. I am still a novice at mySQL... but learning slowly and understand (minimally) how string variables can be used to create altered queries.
Here is my code;
echo "<p><h5>Change address:</h5>";
//get user id when the login/visit page
$userid = get_current_user_id();
$loop = new WP_Query( $args );
//form start
echo '<form method = "post" action = "'. $_SERVER['PHP_SELF'] .'">';
//dropdown menu for collecting SKU of product
echo '<br><select name="sku">';
echo '<option>-- Select product--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
endwhile;
echo '</select>';
//hidden input for userid
echo '<input type="hidden" id="userid" name="userid" value="' . $userid . '">';
//textbox for address
echo '<br><input type="text" value="Insert new address here" id="address" name="address" size="40" />';
//submit button
echo '<br><input type="submit" name="submit">';
echo '</form>';
//write to database
if(isset($_POST['submit'])) {
$user = $_POST['userid'];
$sku = $_POST['sku'];
$address = $_POST['address'];
$con2 = mysqli_connect("IP","user","password","wpdb");
$updateaddress = "REPLACE INTO wp_newaddress(user, sku, address) VALUES($user, $sku, $address)";
$retval = mysqli_query($con2,$updateaddress);
if($retval)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($con2);
}
Thanks :)
You need to use prepare and execute with bound parameters to avoid the SQL injection risk.
You need to check for error conditions after every prepare and execute, and output any errors to your error log. You won't see errors if you don't do this.
Of course you should also watch your PHP error log (which is typically the same as your http server error log), but this goes without saying. Every PHP developer should be watching the error log (even though many developers don't know this).
Here's an example:
$user = $_POST['userid'];
$sku = $_POST['sku'];
$address = $_POST['address'];
$con2 = mysqli_connect("IP","user","password","wpdb");
$updateaddress = "REPLACE INTO wp_newaddress (user, sku, address) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($con2,$updateaddress);
if ($stmt) {
mysqli_stmt_bind_param($stmt, 'sss', $user, $sku, $address);
$ok = mysqli_stmt_execute($stmt);
if ($ok) {
echo 'Data Updated';
} else {
echo 'Data Not Updated';
error_log(mysqli_stmt_error($stmt));
}
mysqli_stmt_close($stmt);
} else {
error_log(mysqli_error($con2));
}
mysqli_close($con2);
Also read answers in How can I prevent SQL injection in PHP?
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below.
Here is my php file;
<?php
$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$sql="SELECT id,planname,price FROM plan";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
echo "<select name=planname value=''>Plan Name</option>"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[id]>$row[planname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
if(isset($_REQUEST['planname'])){
// connection should be on this page
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
$res = mysql_fetch_assoc($sql);
echo $res['price'];die;
}
echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';
?>
I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?
$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
You are searching in the column planname, but by defining the <option>'s as
echo "<option value=$row[id]>$row[planname]</option>";
You are sending the id as value.
So your query should be:
$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));
Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?
The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.
How to do implement your plan
You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)
1. The frontend:
As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).
To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.
So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.
Note:
I am not really familiar with vanilla javascript, so I just followed a
tutorial http://www.w3schools.com/ajax/ajax_php.asp
I think you should check out jQuery if you haven't yet, it makes things really really easy.
Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.
I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function getPrice(id){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonObj = JSON.parse(xmlhttp.responseText);
if(jsonObj.success === true){
document.getElementById("price").value = jsonObj.price;
}else{
document.getElementById("price").innerHTML = jsonObj.message;
}
}
};
xmlhttp.open("GET", "ajax.php?id=" + id, true);
xmlhttp.send();
}
</script>
</head>
<body>
<select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
<?php foreach ($rows as $row): ?>
<option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
<?php endforeach; ?>
</select>
<input type="text" name="price[]" value="" id="price" disabled="disabled">
<p id="error"></p>
</body>
2. The backend: (in this case called ajax.php)
A simple piece of code, nothing special to do.
First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.
Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.
Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.
Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.
<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';
if(!isset($_GET['id'])){
echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
exit;
}
try {
$conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
trigger_error("Connection failed: " . $e->getMessage());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
exit;
}
$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result === false){
trigger_error('Query failed: ' . $conn->errorInfo());
echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
exit;
} else {
echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
exit;
}
I'm trying to get my query to work for this PHP but I'm getting a "Invalid Parameter Number: number of bound variables do not match number of tokens" This is a snippet of my PHP:
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("configmob.php");
//if posted data is not empty
if (!empty($_POST)) {
//If the username or password is empty when the user submits
//the form, the page will die.
//Using die isn't a very good practice, you may want to look into
//displaying an error message within the form instead.
//We could also do front-end form validation from within our Android App,
//but it is good to have a have the back-end code do a double check.
if (empty($_POST['FirstName']) || empty($_POST['LastName'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a First Name and a Last Name.";
//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
//if the page hasn't died, we will check with our database to see if there is
//already a user with the username specificed in the form. ":user" is just
//a blank variable that we will change,Spot FROM Reservation WHERE Date = ':Date' AND Time = ':Time' AND Spot = ':Spot' ";
//now lets update what :user should be
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':TimeIn' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this Reservation is already Taken";
die(json_encode($response));
}
//If we have made it here without dying, then we are in the clear to
//create a new user. Let's setup our new query to create a user.
//Again, to protect against sql injects, user tokens such as :user and :pass
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Gname' => $_POST['Garage'],
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Reservation Added!!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: loginmob.php");
//die("Redirecting to loginmob.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
Thank you for the help!
This is what I found in your second statement:
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':Time' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
Your :TimeIn should be :Time like follows:
$query_params = array(':Date' => $_POST['Date'] , ':Time' => $_POST['Time'] , ':Spot' => $_POST['Spot']
Update:
Also in your second query you have :Garno missing, please try the following:
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Garno' => $_POST['Garno'], // Hopefully $_POST['Garno'] is what you want.
':EmpID' => $_POST['EmpID'], // Hopefully $_POST['EmpID'] is what you want.
':CustID' => $_POST['CustID'], // Hopefully $_POST['CustID'] is what you want.
':License' => $_POST['License'], // Hopefully $_POST['License'] is what you want.
':Floor' => $_POST['Floor'], // Hopefully $_POST['Floor'] is what you want.
':TimeOut' => $_POST['TimeOut'], // Hopefully $_POST['TimeOut'] is what you want.
':Gname' => $_POST['Garage'], // You don't need this, remove this.
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);
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.