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.
Related
I have a database with some rows of data that display on a webpage. Now, I am looking for a way to link each 'ID' field in mysql to a button so that when the button is clicked, a php script will run that deletes the row of mysql information associated with that ID.
I know this is incorrect but I think its close. Just don't know about the php portion inside the id tag. Help?
<form action="remove.php" method="post">
<input type="submit" value="Remove Entry" id="<?php $row['id'] ?>" />
</form>
Am I even on the right path?
Would remove.php look like...
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "DELETE from newcars (stock, year, make, model, trim)
WHERE ('$_POST[id] = $row[id]');
if(mysqli_query($conn, $sql)){
echo "Records deleted successfully.";
}
else {
echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}
mysql_close($conn)
?>
Any help would be greatly appreciated.
Thank you!
HTML:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
You want to pass the ID in a form element, NOT with the submit button.
The PHP would look like this - and this is more secure than your original code as it uses prepared statements.
<?php
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$stmt = $conn->prepare("DELETE FROM newcars WHERE id = ?");
// prepare() can fail because of syntax errors, missing privileges, ....
if(false === $stmt) {
// and since all the following operations need a valid/ready statement object
// it doesn't make sense to go on
// you might want to use a more sophisticated mechanism than die()
// but's it's only an example
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('i', $_POST['id']);
// bind_param() can fail because the number of parameter doesn't match the placeholders in the statement
// or there's a type conflict(?), or ....
if(false === $rc) {
// again execute() is useless if you can't bind the parameters. Bail out somehow.
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc = $stmt->execute();
// execute() can fail for various reasons. And may it be as stupid as someone tripping over the network cable
// 2006 "server gone away" is always an option
if(false === $rc) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->close();
//redirect page back to view page
?>
If you want your Id be posted, it should be like this:
<form action="remove.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$row['id']; ?>">
<input type="submit" value="Remove Entry" />
</form>
Post a hidden field with the name id and the value $row['id'].
And you should take care of the comments above to avoid mysql-injection in your php.
I have been breaking my head around this html/php/mysqli thing and I can't get it to work. I used several echo statements to see what type of error I am facing but nothing shows up when I am trying to post data into my database.
I have used echo $_POST['name of input']; , print_r($_POST); and only on the 1st one I can see my post. So I think it is posting correctly, right?!
I for some strange reason can't find the problem in my code. I have searched for quiet some time on the web but with little to no result.
This is my HTML:
<html>
<head><title>Test2017</title></head>
<body>
<form action="insert.php" method="post">
<table width="400" border="0" cellspacing="10">
<tr>
<td>voornaam:</td>
<td><input type="text" name="voornaam"></td>
</tr>
<tr>
<td>roepnaam</td>
<td><input type="text" name="roepnaam"></td>
</tr>
<tr>
<td>tussenvoegsel</td>
<td><input type="text" name="tussenvoegsel"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" name="achternaam"></td>
</tr>
<tr>
<td><input type="submit" value="registreren!"></td>
</tr>
</table>
</form>
</body>
</html>
and this my insert.php, and also at the VALUES i have tried "''",'' and "" but non of that worked.
<?php
$connect=mysqli_connect("localhost","root","usbw","test");
//check connection
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
$voornaam= mysqli_real_escape_string($connect, $_POST['voornaam']);
$roepnaam= mysqli_real_escape_string($connect, $_POST['roepnaam']);
$tussenvoegsel= mysqli_real_escape_string($connect, $_POST['tussenvoegsel']);
$achternaam= mysqli_real_escape_string($connect, $_POST['achternaam']);
$sql="INSERT INTO user (voornaam,roepnaam,tussenvoegsel,achternaam) VALUES ('$voornaam','$roepnaam','$tussenvoegsel','$achternaam')";
if (!mysqli_query($connect,$sql)) {
die('Error: ' . mysqli_error($connect));
}
echo "1 record added";
mysqli_close($connect);
?>
You guys are my only help, because I am pulling my hair out for this.
Thank you in advance!
I have typed the HTML code first and I have pasted it everywhere else even in the database. So I would not have a problem like that. It is all lowercase.
I reformatted your original example to use a prepared statement, as this is safer for handling user generated input. I added a try catch around your code to attempt to raise visibility on whatever error you are running into
<?php
// ensure reporting for mysql is on.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Subbing out what you had for db connection to illustrate what each
// of those parameters should point to on your local db
$database = new mysqli('host', 'user', 'password', 'db_schema');
// guessing on whether these are strings.
$voornaam = filter_input(INPUT_POST, 'voornaam', FILTER_SANITIZE_STRING);
$roepnaam = filter_input(INPUT_POST, 'roepnaam', FILTER_SANITIZE_STRING);
$tussenvoegsel = filter_input(INPUT_POST, 'tussenvoegsel', FILTER_SANITIZE_STRING);
$achternaam = filter_input(INPUT_POST, 'achternaam', FILTER_SANITIZE_STRING);
// Formatting for readability, parameterized query
$query = "INSERT INTO user (
voornaam,
roepnaam,
tussenvoegsel,
achternaam
) VALUES ( ?, ?, ?, ?)";
// prepare query statement
$stmt = $database->prepare($query);
// bind parameters and types to statement
$stmt->bind_param('ssss', $voornaam, $roepnaam, $tussenvoegsel, $achternaam);
// execute
$stmt->execute();
echo 'Records added: ' . $stmt->affected_rows;
$stmt->close();
$database->close();
} catch (Exception $e) {
// basic print error to screen error handling, not ideal for
// anything other than testing :)
echo $e->getCode() . ' - ' . $e->getMessage();
}
Ok, we have probably totally confused you now, so try this
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$connect=mysqli_connect("localhost","root","usbw","test");
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
// using 4 ? one for each column value in the query
$sql="INSERT INTO user
(voornaam,roepnaam,tussenvoegsel,achternaam)
VALUES (?,?,?,?)";
$stmt = $connect->prepare($sql);
// pass the actual data for each parameter, in order
// the 'ssss' in this case denotes that all 4 params are strings
// they can be s=string, i=integer,b=blob, d=decimal
$stmt->bind_param('ssss',
$_POST['voornaam'],
$_POST['roepnaam'],
$_POST['tussenvoegsel'],
$_POST['achternaam']
);
$result = $stmt->execute();
if ( $result ) {
echo "1 record added";
} else {
echo $connect->error;
}
}
?>
Getting an error of
"Error: 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.
#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."
#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.
Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.
I need to do an school assigment and I have run into quite few problems, but I don't understand why the code below gives empty values to the table. Only NOW() gets inserted into
the table, otherwise it says Query Empty or something like that. I had the same code on different page and with different table and it worked like a charm.
Regards,
Werner.
<?php
$dbhost = 'localhost';
$dbuser = '';
$dbpass = '';
$pnimi =$_REQUEST['pitsa_nimi'];
$id =$_REQUEST['pitsatyybinimi'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO tellimused_pitsad '.
'(pitsa_nimi,aeg,toidutyybi_id)'.
"VALUES ( '$pnimi', NOW(), '$id' )";
mysql_select_db('carl.reinomagi');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo mysql_error();
echo "Entered data successfully\n";
mysql_close($conn);
header("location:tellimine.php");
?>
This is the previous page ( ordering ) code :
<?php
$tulemus = mysql_query("SELECT * FROM pitsad, pitsatyybid WHERE pitsad.toidutyybi_id = pitsatyybid.id", $dbhandle);
while ($row = mysql_fetch_assoc($tulemus))
{
?>
<tr><form action="telli.php">
<td><? echo $row['pitsa_nimi']; ?></td>
<td><? echo $row['hind']; ?></td>
<td><? echo $row['valmimisaeg']; ?> Minutit</td>
<td><? echo $row['pitsatyybinimi']; ?></td>
<td>
<input type="submit" value="TELLI"/>
</form></td>
</tr>
<?php
}
?>
</table>
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a better example using PDO. This code is completely safe against SQL Injection, and is better than using mysql_* functions.
Make sure to read the comments and understand the code.
This is not copy/paste ready code!!
<?php
# Database Connection #
try {
$conn = new PDO("mysql:host=localhost;dbname=carl.reinomagi", "root", ""); //Please consider having different credentials.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Throw Exceptions on errors - This disables the need to check for errors, see the catch block below.
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //True prepared statements.
## Prepreations ##
$pnimi = $_POST["pitsa_nimi"];
$id = $_POST["pitsatyybinimi"]; //Please use $_POST or $_GET rather than $_REQUEST
## Data validation ##
if (empty($pnimi) || empty($id)) {
//One of the variables is empty, return an error to the user.
}
//Few things about this:
//Note the `backticks` around table and column names. This helps readability.
//Also note the placeholders :pnimi and :id, those placeholders for the prepared statement.
$query = "INSERT INTO `tellimused_pitsad` (`pitsa_nimi`, `aeg`, `toibutyybi_id`) VALUES (:pnimi, NOW(), :id);";
$statement = $stmt->prepare($query);
$statement->bindValue(":pnimi", $pnimi); //Bind the values to the placeholders
$statement->bindValue("id", $id);
$statement->execute();
header("Location: tellimine.php");
}
catch (PDOException $e) {
echo "An error has occured! " . $e->getMessage(); //Echo a generic error to all mysql error messages.
}
On form submit, I'm getting a blank page (insert.php) with no error and no success message.
This is the form:
<form action="insert.php" method="post">
Firstname: <input type="text" name="first_name" id="first_name" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
This is the script:
mysql_select_db("my_db", $con);
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
$stmt->execute(':first_name', $first_name);
if (!mysql_query($stmt,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Youre trying to use 2 different MySQL interfaces at the same time. The mysql_* family of functions use the ext/mysql extension... The prepared statement stuff is PDO. You need to choose one or the other. Since PDO is really the way to go ill give you an example with that:
$db = new PDO($dsn, $user, $password);
try {
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
if($stmt->execute(array(':first_name' => $first_name))) {
echo "1 record added";
}
} catch (PDOException $e) {
die('Error: ' . $e->getMessage());
}
The docs on the Mysql DSN (the first argument to the PDO constructor) can be found here.
You need to create a PDO object to be able to use prepared statements. Instead you have opened a connection with mysql_connect(). The two do not mix, and PDO is preferred between them as it is more easily secured through the use of prepared statements (among other reasons).
From the PDO docs:
// This establishes your connection using PDO.
// The PDO connection object is $db
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Pass an associative array to execute(), rather than a list of arguments representing your placeholders. The
// Now that the PDO object is successfully created, prepare your statement
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
// Arg to execute() should be an associative array
$stmt->execute(array(':first_name' => $first_name));
The following call to mysql_query() is unnecessary, as you have already executed the prepared statement with PDO.
// Don't do this
// mysql_select_db("my_db", $con);
// Or this...
//if (!mysql_query($stmt,$con))
//{
// die('Error: ' . mysql_error());
//}
// Or this...
// mysql_close($con)