000webhosting database won't let me send values to phpmyadmin - php

I'm trying to insert from data into my database but it won't work for some reason. I keep getting the following error when submitting the form: Error: INSERT INTO voorwerpenlijst (beschrijving, waar, wanneer, ophalen) VALUES ('value', 'value', 'value', 'value')
Access denied for user 'id11961846_profielwerkstuk'#'%' to database 'voorwerpenlijst'. When i leave out the $sql part i am able to connect to the database just fine so the login credentials are correct. I ran the same PHP using XAMPP and phpmyadmin from my own PC and it worked just fine. This confirmed for me that my code should be fine, but it's still not working with 000webhost. I'm using the database I got through 000webhosting which doesn't allow me to change any of the privileges in phpmyadmin. Any sql statement i try to use gets blocked.
thanks in advance
<html lang="nl">
<meta charset = "utf-8">
<head>
<link rel="stylesheet" href="profielwerkstukSTYLE.css">
<ul>
<li>Home</li>
<li><a class="active" href="upload.php">upload voorwerp</a></li>
<li>voorwerp lijst</li>
</ul>
</head>
<body>
<h3>Upload het door u gevonden voorwerp<h3><br>
<div>
<form action="upload.php" method="post" enctype="multipart/form-data">
Beschrijving:<br> <input type="text" name="beschrijving" placeholder="bijv. jas, airpods, sleutels etc."><br>
Waar:<br> <input type="text" name="waar" placeholder="bijv. lokaal 117"><br>
Wanneer:<br> <input type="text" name="wanneer" placeholder="bijv. 5e uur"><br>
ophalen waar:<br> <input type="text" name="ophalen" placeholder="bijv. bij de balie"><br>
<input type="submit" value="verzend" name="knop">
</form>
<div>
<?php
if(
isset($_POST["beschrijving"])&& $_POST["beschrijving"]!="" &&
isset($_POST["waar"]) && $_POST["waar"]!="" &&
isset($_POST["wanneer"]) && $_POST["wanneer"]!="" &&
isset($_POST["ophalen"]) && $_POST["ophalen"]!="")
{
$host="localhost";
$username="id11961846_profielwerkstuk";
$password="12345";
$dbname="voorwerpenlijst";
$conn= mysqli_connect("$host", "$username", "$password", "$dbname");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$beschrijving=$_POST["beschrijving"];
$waar=$_POST["waar"];
$wanneer=$_POST["wanneer"];
$ophalen=$_POST["ophalen"];
$sql = "INSERT INTO voorwerpenlijst (beschrijving, waar, wanneer, ophalen)
VALUES ('$beschrijving', '$waar', '$wanneer', '$ophalen')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
else
{
if(isset($_POST["knop"]))
{
print("Vul A.U.B alles in");
}
}
?>
</body>
</html>

Your code is vulnerable to SQL injection - a better way to perform this insert would be to use a prepared statement ~ it might help solve your issue too
<?php
$errors=[];
$args=array(
'beschrijving' => FILTER_SANTITIZE_STRING,
'waar' => FILTER_SANTITIZE_STRING,
'wanneer' => FILTER_SANTITIZE_STRING,
'ophalen' => FILTER_SANTITIZE_STRING,
'knop' => FILTER_SANTITIZE_STRING
);
foreach( array_keys( $args ) as $field ){
if( !isset( $_POST[ $field ] ) ) $errors[]=sprintf( 'The field "%s" is not set', $field );
}
foreach( $_POST as $field => $value ){
if( !in_array( $field, array_keys( $args ) ) )$errors[]=sprintf( 'Unknown field "%s"', $field );
}
if( empty( $errors ) ){
/* filter incoming POST array */
$_POST=filter_input_array( INPUT_POST, $args );
/* create variables */
extract( $_POST );
$host="localhost";
$username="id11961846_profielwerkstuk";
$password="12345";
$dbname="voorwerpenlijst";
$conn=new mysqli( $host, $username, $password, $dbname );
$sql='insert into `voorwerpenlijst` ( `beschrijving`, `waar`, `wanneer`, `ophalen` ) values (?,?,?,?)';
$stmt=$conn->prepare( $sql );
if( !$stmt )$errors[]='failed to prepare sql';
$stmt->bind_param( 'ssss', $beschrijving, $waar, $wanneer, $ophalen );
$res=$stmt->execute();
$stmt->close();
echo $res ? 'New record created successfully' : 'error';
} else {
/* display errors? */
}
?>

Related

Why doesn't my UPDATE query work? MySQL

I'm working on a blog website and i'm currently stuck at making a blog edit page. For some reason my blog UPDATE query doesn't work, and i can't figure out why it isn't working. I'm not getting an error. It is just not updating anything.
I'm collecting the data from an old blog and inserting it into my form. And then I'm trying to update it using my update query.
This is my code so far:
aanpassen.php
<?php
$error=false;
include_once('includes/connection.php');
include_once('includes/article.php');
$article = new Article;
if ( isset( $_POST ['id'], $_POST['title'], $_POST['content'] ) ) {
$id = $_POST ['id'];
$title = $_POST['title'];
$content = nl2br( $_POST['content'] );
if (empty($title) || empty($content) || empty($id)){
$error='All fields are required!';
} else {
$query = $pdo->prepare("UPDATE articles SET article_title = :title,
article_content = :content WHERE id=:id");
if( $query ){
$id = $_POST ['id'];
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
} else {
exit('bad foo - unable to prepare sql query');
}
}
}
if ( isset( $_GET['id'] ) ) {
$id = $_GET['id'];
$data = $article->fetch_data( $id );
} else {
header('Location: index.php');
exit();
}
?>
<form action="aanpassen.php" method="post" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="title" class="titleform" placeholder="Blog naam" value="<?php echo $data['article_title']; ?>" />
<textarea name="content" id="summernote" rows="15" cols="50"><?php echo $data['article_content'] ?></textarea>
<input type="submit" class="buttonclass" value="Aanmaken" />
</form>
<?php
if ($error)
printf('<h1>%s</h1>', $error);
?>
connection.php
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=cms', 'root', 'root');
} catch (PDOException $e) {
exit('Database error.');
}
?>
you missed ":" in all the bindValue arguments. should be like this:
$query->bindValue(':title', $title);
$query->bindValue(':content', $content);
$query->bindValue(':id', $id);
and also if (empty($title) or empty($content) or empty($id)) this should be if (empty($title) || empty($content) || empty($id)) like this
When you access aanpassen.php initially it's in this format right - aanpassen.php?id=1??
Otherwise your code seems fine when I tested it.
Just Change:
$query->execute();
header( sprintf( 'Location: index.php?status=%s', $result ? 'ok' : 'failed' ) );
To:
$success = $query->execute();
header( 'Location: index.php?status='.( $success ? 'ok' : 'failed' ) );exit();

Why every time f5(refresh) is my website insert data to the database

I have a form that inserts data into the database using mysql. When I click submit (add data) the data is inserted into the database successfully. However, when I press f5 (refresh), the data is still inserted into the database. I do not know where I'm wrong. Please help me. This is my code:
<?php
$username = "user_tintuc"; // Khai báo username
$password = "123456"; // Khai báo password
$server = "localhost"; // Khai báo server
$dbname = "tintuc"; // Khai báo database
// Kết nối database tintuc
$connect = new mysqli($server, $username, $password, $dbname);
//Nếu kết nối bị lỗi thì xuất báo lỗi và thoát.
if ($connect->connect_error) {
die("Không kết nối :" . $conn->connect_error);
exit();
}
//Khai báo giá trị ban đầu, nếu không có thì khi chưa submit câu lệnh insert sẽ báo lỗi
$title = "";
$date = "";
$description = "";
$content = "";
//Lấy giá trị POST từ form vừa submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["title"])) { $title = $_POST['title']; }
if(isset($_POST["date"])) { $date = $_POST['date']; }
if(isset($_POST["description"])) { $description = $_POST['description']; }
if(isset($_POST["content"])) { $content = $_POST['content']; }
//Code xử lý, insert dữ liệu vào table
$sql = "INSERT INTO tin_xahoi (title, date, description, content)
VALUES ('$title', '$date', '$description', '$content')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
//Đóng database
$connect->close();
?>
<form action="" method="post">
<table>
<tr>
<th>Tiêu đề:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô tả:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>Nội dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">Gửi</button>
</form>
I edited it like this. But it's still like that.
if (isset($_POST['submit'])){
if(isset($_POST["date"])) { $date = $_POST['date'];}
if(isset($_POST["MAB"])) { $MAB = $_POST['MAB']; }
if(isset($_POST["MBA"])) { $MBA = $_POST['MBA']; }
if(isset($_POST["PAB"])) { $PAB = $_POST['PAB']; }
if(isset($_POST["PBA"])) { $PBA = $_POST['PBA']; }
$sql = "INSERT INTO `dbsht` (`date`, `MAB`, `MBA`, `PAB`, `PBA`) VALUES ('$date', '$MAB', '$MBA', '$PAB', '$PBA')";
if ($connect->query($sql) === TRUE) {
echo "Thêm dữ liệu thành công";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
}
This is normal issues. You should use POST-Redirect-GET pattern to prevent it. After insert database successful, you should response with redirect to GET request.
You may try
if ($connect->query($sql) === TRUE) {
$_SESSION["ADD_SUCCESS"] = 1;
header('Location: '.$_SERVER['REQUEST_URI']);
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
For successful message
//Đóng database
$connect->close();
if(isset($_SESSION["ADD_SUCCESS"]))
{
echo "Chúc mừng bạn đã thêm dữ liệu thành công";
unset($_SESSION["ADD_SUCCESS"]);
}
You can fix it, but don't, reorganize it and rewrite it because your approach is border-line terrible.
Have myform.html as one file, your php code for inserting data in db as another file like db_insert.php and your data for db connection (user, pass, db, host) in separate file OUTSIDE of public folder (outside public_html or whatever) in file config.inc.php, for example. Do this and you'll avoid this problem that you have right now and many others.
So in myform.html enter data and submit => db_insert.php gets data from myform.html, fetches data from config.inc.php, enters it in DB and redirects back to myform.html or some other part of your application.
After you make it work and figure it out how and why, then read a few articles about AJAX and how to do the same job without leaving your form page. It's obvious that you just started learning, so make sure you learn it the right way ;)
Once the POST request has been sent the php code should do the necessary logic tests and sanitation routines on the data, construct and execute the sql and finally redirect to either the same page or another. The redirect will prevent the form being re-submitted when refreshing the page
<?php
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
try{
$username = "user_tintuc";
$password = "123456";
$server = "localhost";
$dbname = "tintuc";
$connect = new mysqli( $server, $username, $password, $dbname );
$title = isset( $_POST["title"] ) ? $_POST["title"] : false;
$date = isset( $_POST["date"] ) ? $_POST["date"] : false;
$description = isset( $_POST["description"] ) ? $_POST["description"] : false;
$content = isset( $_POST["content"] ) ? $_POST["content"] : false;
if( $title && $date && $description && $content ){
$sql = 'insert into `tin_xahoi` ( `title`, `date`, `description`, `content`) values (?,?,?,?)';
$stmt=$connect->prepare( $sql );
if( $stmt ){
$stmt->bind_param('ssss',$title,$date,$description,$content);
$result=$stmt->execute();
$stmt->close();
/* set a temporary session variable - used to display message */
$_SESSION['dbstatus']=$result ? 'Record added' : 'Sorry - an error occurred';
header('Location: ?status=' . ( $result ? 'ok' : 'error' ) );
} else {
throw new Exception('Failed to prepare sql');
}
} else {
throw new Exception('one or more variables are empty');
}
}catch( Exception $e ){
$message=sprintf('<p>%s</p>',$e->getMessage());
}
}
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<th>Tiêu d?:</th>
<td><input type="text" name="title" value=""></td>
</tr>
<tr>
<th>Ngày tháng:</th>
<td><input type="date" name="date" value=""></td>
</tr>
<tr>
<th>Mô t?:</th>
<td><input type="text" name="description" value=""></td>
</tr>
<tr>
<th>N?i dung:</th>
<td><textarea cols="30" rows="7" name="content"></textarea></td>
</tr>
</table>
<button type="submit">G?i</button>
<?php
/* Display the message from session variable and unset the variable */
if( !empty( $_GET['status'] ) && isset( $_SESSION['dbstatus'] ) ) {
$message=$_SESSION['dbstatus'];
unset( $_SESSION['dbstatus'] );
}
/* Display whatever is in $message */
echo $message;
?>
</form>
</body>
</html>

Can't insert text with apostrophe [duplicate]

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>

Website form not submitting data to mssql database

I have spent days trying to figure how to get form data on my webpage to insert into my employee table on the forklift database mssql. when i click submit on the form it refreshes the page with Connection established but no data in the database.
<?php
/* Connect using Windows Authentication. */
$serverName = "EXAMPLE";
$connectionOptions = array("Database"=>"FORKLIFT");
/* Connect using Windows Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionOptions);
if($conn)
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
if(empty($_POST) === false && empty($errors)=== true)
{
//assign form input to variables
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATEOFBIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
/*Insert data.*/
$INSERT_ROW = $query = "INSERT INTO
EMPLOYEE(FIRSTNAME,LASTNAME,DATEOFBIRTH,PHONENUMBER,ADDRESS)
VALUES ('$FIRSTNAME','$LASTNAME','$DATEOFBIRTH','$PHONENUMBER','$ADDRESS')";
$result = sqlsrv_prepare($conn,$query)or die('Error querying MSSQL
database');
sqlsrv_execute($result);
}
?>
HTML
<form name="submit" action="employee.php" method="POST" >
<h2>Register New Member</h2>
<table border="0">
<tr>
<td>FIRSTNAME</td>
<td>
<input type="text" name="FIRSTNAME" id="FIRSTNAME"/>
</td>
</tr>
<tr>
<td>LASTNAME</td>
<td>
<input type="text" name="LASTNAME" id="LASTNAME"/>
</td>
</tr>
<tr>
<td>DATE_OF_BIRTH</td>
<td>
<input type="date" name="DATE_OF_BIRTH" id="DATE_OF_BIRTH"/>
</td>
</tr>
<tr>
<td>PHONENUMBER</td>
<td>
<input type="text" name="PHONENUMBER" id="PHONENUMBER"/>
</td>
</tr>
<tr>
<td>ADDRESS</td>
<td>
<input type="text" name="ADDRESS" id="ADDRESS"/>
</td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" name="submit" value="REGISTER"/></td>
</tr>
</table>
I noticed that you are attempting to post data to a database, that is not actually named correctly on the PHP side, this would just result in the information related to your DATE OF BIRTH not being posted in the first place, as it has to match the PHP side exactly when you declare to retrieve posted data. I am pretty sure from memory that you only need to change the name in the form on the client side to DATEOFBIRTH, or you will have to change the PHP side to DATE_OF_BIRTH instead of this, whilst keeping the client side as DATE_OF_BIRTH
<input type="date" name="DATE_OF_BIRTH" id="DATE_OF_BIRTH"/>
NEEDS TO BE:
<input type="date" name="DATEOFBIRTH" id="DATEOFBIRTH"/>
I made a couple of minor alterations but cannot test to see - run it and see what the resultant sql statement looks like. I hope it helps.
<?php
if( !empty( $_POST ) && isset( $_POST["FIRSTNAME"], $_POST["LASTNAME"], $_POST["DATE_OF_BIRTH"], $_POST["PHONENUMBER"], $_POST["ADDRESS"] ) ) {
/*
There is no point creating a db connection if a later condition fails
so create the db conn after testing key variables are set
*/
$server = "EXAMPLE";
$options = array( "Database"=>"FORKLIFT" );
$conn = sqlsrv_connect( $server, $options );
/* In production environment do not display actual errors! */
if( !$conn ) die( print_r( sqlsrv_errors(), true ) );
/* as pointed out by #Daniel Rutter, the field is actually called `DATE_OF_BIRTH` */
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATE_OF_BIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
$sql = "INSERT INTO EMPLOYEE
( FIRSTNAME,LASTNAME,DATEOFBIRTH,PHONENUMBER,ADDRESS )
VALUES
( '$FIRSTNAME','$LASTNAME','$DATEOFBIRTH','$PHONENUMBER','$ADDRESS' )";
/* Comment out the following line after running the script and observing the output here */
exit( $sql );
/* I assume that `sqlsrv_prepare` returns either true or false */
$stmt = sqlsrv_prepare( $conn, $sql ) or die( 'Error querying MSSQL database' );
if( $stmt ) sqlsrv_execute( $stmt );
/* debug post vars */
} else { echo 'Error::' . print_r($_POST,true ); }
?>
Having briefly had a look at the online PHP manual for the various sqlsrv_* commands perhaps you ought to try along these lines - it follows closely with one of the examples given - though it is untested due to not having a mssql server instance to play with.
<?php
if( !empty( $_POST ) && isset( $_POST["FIRSTNAME"], $_POST["LASTNAME"], $_POST["DATE_OF_BIRTH"], $_POST["PHONENUMBER"], $_POST["ADDRESS"] ) ) {
/*
There is no point creating a db connection if a later condition fails
so create the db conn after testing key variables are set
*/
$server = "EXAMPLE";
$options = array( "Database"=>"FORKLIFT" );
$conn = sqlsrv_connect( $server, $options );
/* In production environment do not display actual errors! */
if( !$conn ) die( print_r( sqlsrv_errors(), true ) );
$FIRSTNAME = $_POST["FIRSTNAME"];
$LASTNAME = $_POST["LASTNAME"];
$DATEOFBIRTH = $_POST["DATE_OF_BIRTH"];
$PHONENUMBER = $_POST["PHONENUMBER"];
$ADDRESS = $_POST["ADDRESS"];
$sql = "INSERT INTO EMPLOYEE
( FIRSTNAME, LASTNAME, DATEOFBIRTH, PHONENUMBER, ADDRESS )
VALUES
( ?,?,?,?,? )";
$params=array(
&$FIRSTNAME,
&$LASTNAME,
&$DATEOFBIRTH,
&$PHONENUMBER,
&$ADDRESS
);
/* add the posted variables as an array here as the third arg */
$stmt = sqlsrv_prepare( $conn, $sql, $params ) or die( 'Error querying MSSQL database' );
if( $stmt ) sqlsrv_execute( $stmt );
/* debug post vars */
} else {
echo 'Error::' . print_r( $_POST, true );
}
?>
From the PHP online manual regarding sqlsrc_prepare:
Prepares a query for execution. This function is ideal for preparing a
query that will be executed multiple times with different parameter
values.
and
When you prepare a statement that uses variables as parameters, the
variables are bound to the statement. This means that if you update
the values of the variables, the next time you execute the statement
it will run with updated parameter values. For statements that you
plan to execute only once, use sqlsrv_query().

SQL Database password protected submission

How do I make the following database only submit the entries if the password matches '1996' - I have tried looking into this and can't find out anything. The following could also have a display.php file that has the database details on and they also have the correct pin coding. I just don't know how to make this part of the coding make sure the pin is correct before submitting the details and if the pin is incorrect then an error message apears.
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $db;
var $pin;
public function display_public() {
$q = "SELECT * FROM sianDB4 ORDER BY created DESC LIMIT 4";
$r = mysql_query($q);
$entry_display = '';
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$title = ($a['title']);
$bodytext = ($a['bodytext']);
$author = ($a['author']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$title
</h2>
<h3>
$bodytext
</h3>
<p>
$author
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="title">Title:</label><br />
<input name="title" id="title" type="text" maxlength="150" />
<div class="clear"></div>
<label for="bodytext">Body Text:</label><br />
<textarea name="bodytext" id="bodytext"></textarea>
<div class="clear"></div>
<label for="author">Author:</label><br />
<textarea name="author" id="author"></textarea>
<div class="clear"></div>
<label for="pin">Pin:</label><br />
<input name="pin" id="pin" type="Password" maxlength="4" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['title'] )
$title = mysql_real_escape_string($_POST['title']);
if ( $_POST['bodytext'])
$bodytext = mysql_real_escape_string($_POST['bodytext']);
if ( $_POST['author'])
$author = mysql_real_escape_string($_POST['author']);
if ( $title && $bodytext && $author ) {
$created = time();
$sql = "INSERT INTO sianDB4
VALUES( '$title','$bodytext','$author','$created')";
return mysql_query($sql);
}else{
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password,$this->pin) or die("Could not connect. " . mysql_error());
mysql_select_db($this->db) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS sianDB4 (
title VARCHAR(150),
bodytext TEXT,
author TEXT,
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
As noted by #Jay, the use of the mysql_* suite of functions is not to be recommended anymore so hopefully you can make use of the code below which uses mysqli instead.
I'm not sure how you were using or presenting the class to the user but you'll no doubt be able to make the necessary changes.
<?php
class simplecms{
/*
Pass in the dbconn as a parameter to this class's constructor
*/
private $db;
private $pin;
public function __construct( dbconn $db=null, $pin=false ){
$this->db=$db;
$this->pin=intval( $pin );
}
public function display_public() {
$sql='select * from `siandb4` order by `created` desc limit 4';
$res=$this->db->query( $sql );
/* use an array rather than concatenating a string for output */
$html=array();
if( $res ){
while( $rs = $res->fetch_object() ){
$html[]="
<div class='post'>
<h2>{$rs->title}</h2>
<h3>{$rs->bodytext}</h3>
<p>{$rs->author}</p>
</div>";
}
} else {
$html[]="
<h2>This Page Is Under Construction</h2>
<p>No entries have been made on this page. Please check back soon, or click the link below to add an entry!</p>";
}
/* hide this from ordinary users somehow */
$html[]="
<p class='admin_link'>
<a href='{$_SERVER['SCRIPT_NAME']}?admin=1'>Add a New Entry</a>
</p>";
/* Add the admin form */
$html[]=$this->display_admin();
/* display stuff */
echo implode( PHP_EOL, $html );
}
public function display_admin() {
$message='';
if( $_SERVER['REQUEST_METHOD']=='POST' ){/* Add record to the db if the pin matches */
$message=$this->write() ? 'Database has been updated' : 'Sorry, unable to add that record - check your PIN is correct';
}
$admin = isset( $_GET['admin'] ) ? intval( filter_input( INPUT_GET, 'admin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
return $admin ? "
<style>
form#admin, form#admin *{display:block;box-sizing:content-box!important;}
form#admin{ width:50%;display:block;clear:both;float:none;margin:0 auto;}
form#admin label{width:100%;clear:both;float:none;margin:0.5rem auto 3rem auto;padding:0.25rem;}
form#admin label input, form#admin textarea{float:right;width:60%;padding:1rem;}
form#span{color:red;}
</style>
<form id='admin' method='post'>
<label for='title'>Title:<input name='title' id='title' type='text' maxlength='150' /></label>
<label for='bodytext'>Body Text:<textarea name='bodytext' id='bodytext'></textarea></label>
<label for='author'>Author:<textarea name='author' id='author'></textarea></label>
<label for='pin'>Pin:<input name='pin' id='pin' type='Password' maxlength='4' /></label>
<input type='submit' value='Create This Entry!' />
<span>{$message}</span>
</form>" : "";
}
public function write(){
$pin = isset( $_POST['pin'] ) ? intval( filter_input( INPUT_POST, 'pin', FILTER_SANITIZE_NUMBER_INT ) ) : false;
$title = isset( $_POST['title'] ) ? filter_input( INPUT_POST, 'title', FILTER_SANITIZE_STRING ) : false;
$bodytext = isset( $_POST['bodytext'] ) ? filter_input( INPUT_POST, 'bodytext', FILTER_SANITIZE_STRING ) : false;
$author = isset( $_POST['author'] ) ? filter_input( INPUT_POST, 'author', FILTER_SANITIZE_STRING ) : false;
if ( $title && $bodytext && $author && $pin===$this->pin ) {
/* ? not sure you really want to run this each and every time but... */
$this->buildtbl();
/* Prepare the sql and execute - return status */
$sql='insert into `sianDB4` set `title`=?, `bodytext`=?, `author`=?;';
$stmt=$this->db->prepare( $sql );
$stmt->bind_param( 'sss', $title, $bodytext, $author );
return $stmt->execute();
}
return false;
}
private function buildtbl(){/* build the table - slightly modified */
$sql='create table if not exists `siandb4` (
`id` int(10) unsigned not null auto_increment,
`title` varchar(150) null default null,
`bodytext` text null,
`author` text null,
`created` timestamp null default current_timestamp,
primary key (`id`)
)engine=innodb;';
$this->db->query( $sql );
}
}//end class
class dbconn{
/* Simple mysqli db connection */
private $conn;
public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
$this->conn=new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
}
public function query( $sql ){
return $this->conn->query( $sql );
}
public function prepare( $sql ){
return $this->conn->prepare( $sql );
}
}//end class
?>
<html>
<head>
<title>Simple CMS - Hello Kitty Example!</title>
<style>
h2,h3{font-size:1rem;}
div.post{font-size:0.85rem;border-bottom:1px dotted gray;margin:0 auto 3rem auto;}
</style>
</head>
<body>
<h1>Simple CMS - Hello Kitty Example!</h1>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxxxxx';
$dbname = 'xxxxxx';
$db=new dbconn( $dbhost, $dbuser, $dbpwd, $dbname );
$cms=new simplecms( $db, 1996 );
$cms->display_public();
$db=$cms=null;
?>
</body>
</html>

Categories