HTTP Error 500 when trying to execucute INSERT INTO sql query - php

I'm fairly new to php and SQL and just can't figure out the problem. Note that this is a school project, therefore the vulnerability to SQL Injections and saving the blank passwords are nothing to worry about.
After the User filled out the Login-form, he's redirected to this page:
[Some html]
<?php
if(isset($_POST['submit']))
{
ConnectSQL();
}
//Retrieve POSTed Login information
$Username = htmlspecialchars($_POST['RegUsername']);
$Email = htmlspecialchars($_POST['RegEmail']);
$Password = htmlspecialchars($_POST['RegPassword']);
function ConnectSQL() {
// SQL Server Extension Sample Code:
// (ConnectionInfo, obviously it's there in the real file)
$conn = sqlsrv_connect($serverName, $connectionInfo);
// PHP Data Objects(PDO) Sample Code:
try {
$conn = new PDO('sqlsrv:server = tcp:xxx.database.windows.net,1433; Database = userdb', 'arechon', '{NotTheRealPassword}');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Successfully connected to SQL Server and DB";
Register();
}
catch (PDOException $e) {
print('Error connecting to SQL Server.');
die(print_r($e));
}
}
function Register($Username, $Email, $Password) {
$regquery = "INSERT INTO dbo.Users (Username, Email, Password) VALUES ('UsernameTest', 'EmailTest', 'PasswordTest')";
$conn->query($regquery);
echo '<script type="text/javascript">window.open("http://xxx.azurewebsites.net/Login.html", "_self");</script>';
The Code always seems to stop at $conn->query($regquery); and doesn't return any error messages. Sometimes it just stops, when I slightly modify the Code (e.g. replacing $conn->query($regquery); with $conn->exec($regquery); or using " instead of ') I get a HTTP500 error.
I found some similiar questions here on stackoverflow as well as on other plattforms, but none of the provided answers could solve this error. Note that I use SQL and NOT MySQL (though it wouldn't be a lot of work to change that if you think that could solve my problem).

Related

PHP script works on my local pc but not on my server

I have a simple PHP script, to take the data enter on a form and store it in mysql database. When I run it on my PC it enters the data correctly, but, when I run it from my online server it display my PHP script on a new page!
Here is my code:
<?php
$servername = "localhost";
$username = "theuser";
$password = "thepassword";
$dbname = "thedb";
$cName['c_name'] = isset($_POST['c_name']);
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);
$sql = "INSERT INTO the_tb (c_name,c_reg,c_tel1,c_tel2,f_name,l_name,m_tel,email_addr1,email_addr2,p_addr1,p_addr2,p_city,p_county,p_code,p_country,contact_message,yes_no) VALUES ('$_POST[c_name]','$_POST[c_reg]','$_POST[c_tel1]','$_POST[c_tel2]','$_POST[f_name]','$_POST[l_name]','$_POST[m_tel]','$_POST[email_addr1]','$_POST[email_addr2]','$_POST[p_addr1]','$_POST[p_addr2]','$_POST[p_city]','$_POST[p_county]','$_POST[p_code]','$_POST[p_country]','$_POST[contact_message]','$_POST[yes_no]')";
// use exec() because no results are returned
$conn->exec($sql);
echo "'$_POST[c_name]','$_POST[c_reg]','$_POST[c_tel1]','$_POST[c_tel2]','$_POST[f_name]','$_POST[l_name]','$_POST[email_addr1]','$_POST[email_addr2]','$_POST[p_addr1]','$_POST[p_addr2]','$_POST[p_city]','$_POST[p_county]','$_POST[p_code]','$_POST[p_country]','$_POST[contact_message]','$_POST[yes_no]'.";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
As I said it works on my local workstation. Now I have checked that I have the same version on PHP installed as well as all the relevant modules and all seem to be the same.
I know that I have made a mistake somewhere but for the life of me I cannot see where. Could one you guys PHP expert can tell me where I went wrong?
Thank you kindly

PHP/mySQL - INSERT INTO not working but also no error

one specific php/mydql command is not working. the sql will not be executed, nor do I get an error message. The sql command executed by HEIDI SQL gives me no error. Query before this command are executed correct. Only this one specific isn't working. I wrote it done one by one as the others which worked perfect before. Heres the code:
$sql = "INSERT INTO users (username,password,email) VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute(array($username, $hash, $email));
The connection.php file code:
global $conn;
$config = [
$dbname = "mysql:host=localhost; dbname=starwardb;",
$login = "root",
$password = ""
];
try {
$conn = new PDO(...$config);
} catch (Exception $ex) {
echo "ERROR: " . $ex;
}
Thank you for any advice!
The mistake was, that the hashing of the password extends the string. The Database length of the password was by 50. I have increased it to 64 and now it works fine.
From: https://stackoverflow.com/revisions/45147068/3

PHP mysqli insert return error invalid request

I've been having a bit of trouble with my PHP code.
I'm trying to insert a new row in table gebruikers.
I'm using a JSON API to post the data from my C# Android app to the server.
running the code returns an invalid request error.
PHP:
function registerUser($api_data)
{
// connection
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$database = "test";
$mysqli = new mysqli($servername, $username, $password, $database);
//check connection
if(mysqli_connect_errno())
{
API_Response(true, 'connection error');
}
$register_data = json_decode($api_data);
$leerlingnummer = intval($register_data->leerlingnummer); //passed as string, int in database
$wachtwoord = $register_data->wachtwoord; //string
$email = $register_data->email; //string
$result = $mysqli->query("INSERT INTO `gebruikers` (`Leerlingnummer`, `Wachtwoord`, `Email`) VALUES ({$leerlingnummer}, {$wachtwoord}, {$email})");
if ($result == false)
{
API_Response(true, "{$mysqli->error}");
}
else
{
API_Response(false, 'SUCCESS');
}
$mysqli->close();
}
database is looking as follows:
database layout
I've never felt this stupid before, but the error came from the fact that I was still referencing to an older .php file. I was so focussed on the PHP script that I didn't notice this error in my app before.
the quotes advised by Sean and fuso were needed later on though so thanks for that.
Problem solved, sorry for wasting some of your time :/
You should quote your data in the insert query.
... VALUES ('{$email}','{$other}')

How can I prevent this script from being freely accessed?

I am trying to create a simple PHP/MySQL message system. The following code is a section of the page that displays the messages a user has received, messages.php. The user's messages have been fetched from MySQL and stored in the variable $messages.
foreach($messages as $message) {
// formatting, printing the text, etc.
echo 'Remove';
}
And here is the file msg_del.php:
<?php
$id = $_GET['id'];
// Connect to the database
require("../info/dbinfo.php");
$db_user = constant("DB_USER");
$db_pass = constant("DB_PASS");
$db_name = constant("DB_NAME");
$db_server = constant("DB_SERVER");
try {
$conn = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("DELETE FROM messages WHERE id = " . $conn->quote($id) . ";");
$stmt->execute();
}
catch(PDOException $e) {
echo "Error connecting to database!";
exit();
}
// Redirect to messages page
header("Location: messages.php");
exit();
?>
The code is fully functional, but the problem is that anyone can type msg_del.php?id=SOMEID into a browser and delete messages. How can I secure this to where messages can only be deleted from the links on messages.php?
You're going to need some sort of token in your request to validate that this is indeed a valid request from your system.
One method would be to append a nonce to your request. This ensures that the request came from a form you control, and someone isn't using an old form to spoof a new request.
There are many nonce libraries for PHP you can choose from.
The script needs to know if the current user has permission to do the action. One simple way to do that is with the $_SESSION variable.
Something like:
session_start();
if (!isset($_SESSION['user_id']) && /*permission logic here*/) {
//display an error message
die();
}
// database query here

try/catch in php not printing anything out

Hey Everyone it has been awhile wince I've worked with try/catch blocks but I would like to start using them again just for purpose of error handling and proper practices. My code is below,
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try {
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//if the connection fails the try/catch block will pick it up
if (!$conn) {
throw new PDOException('Fatal error on connection');
} else {
//prepare and exexcute the query to match the codes up
$stmt = $conn->prepare("SELECT email_code, active from primarydb.user WHERE email_code = ?");
$stmt->bindParam(1, $email_code, PDO::PARAM_STR, 32);
//check to make sure that the statment executes properly
if (!$stmt->execute()){
throw new PDOException("PDO ERROR ON EXECUTION:\n" . $stmt->errorInfo());
} else { //statement has not failed
//get the row count
$count = $stmt->rowCount();
//traverse the results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//there can only be one!
if ($count != 1 || $row['active'] != 0) {
//generate error message
throw new PDOException("Wrong Code");
} else {
echo "working";
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->brindParam(1, 1, PDO::PARAM_INT);
$stmt->bindParam(2, $email_code, PDO::PARAM_STR, 32);
if (!$stmt->execute()) {
throw new PDOException("We're sorry but we can not update your profile at this time, plesae try again later. If this problem persists please contact customer service.");
} else {
print "Your account has now been activated and it is ready to use!";
}
}
}
}
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
I would like to know why I am not getting any of the error messages, and then how do I fix this problem so that I can avoid making the same problems again in the future. If there is something that is missing or if more information is needed please let me know. Otherwise I think it is pretty straight forward.
ADDITIONAL INFO: I have putt a message that says working at each block of if/else and the one it finally stops showing up at is when I check if($count != 1 || $row['active'] != 0)
UPDATE
<?php
$email_code = $_REQUEST['code']; //retrive the code from the user clicked link in the email
//database information
$dsn = 'mysql:host=localhost;dbname=primarydb';
$username = 'root';
$password = '';
try{
//option for PDO allows for prepared SQL statements that will mazimize the prevention of sql injections and malicious attacks on the server and databases
$conn = new PDO($dsn, $username, $password); //establish the connection
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //disable the php parse from parsing the statements.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //allow error mode to be active in order to display any errors which may open up holes to attacks
//prepare the update statement
$stmt = $conn->prepare("UPDATE primarydb.user SET active = ? WHERE email_code = ?");
$stmt->bindParam('is', $a = 1, $email_code);
if($stmt->execute()){
print "Your account has now been activated and it is ready to use!";
}
} catch(PDOException $e){
//display error message if the database has failed in some manner
echo $e->getMessage();
}
?>
Generated new code, I don't want to get off topic, but I would like a complete solution to this problem. I am now getting the following error
Strict Standards: Only variables should be passed by reference in C:\inetpub\wwwroot\mjsite\login\complete_registration.php on line 14
SQLSTATE[HY000]: General error: 2031
Thoughts?
Please read this first line from the PDOException documentation:
Represents an error raised by PDO. You should not throw a PDOException
from your own code.
Just throw and catch regular old Exceptions. This would also catch a PDOException which inherits from it.
This also gives you a much better way to distinguish between actual exception thrown by PDO and your own exceptions. By the way, it would seem you have a number of cases where you are redundantly throwing exception when PDO would have encountered an error and thrown an exception anyway. Only the first exception will be caught, so in many of those cases, your throw would never be executed.
Also why bother with the SELECT before the update at all? YOu are basically just wasting a query because you aren't doing anything with the selected information. Perhaps just go straigth for update and handle cases where email_code doesn't exist.

Categories