PHP - Internal 500 error in function - php

i'm getting 500 internal error in this script for some reason i looked trough the script for like an hour or two cant find the issue in the function, its not an mysql error ether..
function CreateGame($Game, $Pass, $Diff, $CharInfo, $Lad, $Desc, $Realm, $Hash, $timestamp, $Bot = 0)
{
$uno = false;
include "conf.php";
$conn = new mysqli($serverip, $username, $password, $dbname, $Port);
if ($conn->connect_error) {
die("Connection failed: " . encrypt($conn->connect_error);
}
$game = mysqli_escape_string($conn, $Game);
$pass = mysqli_escape_string($conn, $Pass);
$diff = mysqli_escape_string($conn, $Diff);
$hash = mysqli_escape_string($conn, $Hash);
$charInfo = mysqli_escape_string($conn, $CharInfo);
$desc = mysqli_escape_string($conn, $Desc);
$realm = substr($Realm, 0, 1);
$realm = mysqli_escape_string($conn, $Realm);
$bot = mysqli_escape_string($conn, $Bot);
$lad = mysqli_escape_string($conn, $Lad);
$UserResult = $conn->query("SELECT * from user where hash = '$hash'");
if (!$UserResult)
{
echo encrypt("hash not found: ". $hash);
}
while($row = $UserResult->fetch_assoc())
{
if($uno == false)
{
$uno = true;
$BanCheckQuerrt = "SELECT * from hwid where id = '".$row['HWID']."'";
$BanCheckResult = $conn->query($BanCheckQuerrt);
while($BanCheckRow = $BanCheckResult->fetch_assoc())
{
if((int)$BanCheckRow['banned'] === 0)
{
$sql = "INSERT INTO games (Game, Password, Description, Difficulty, Realm, Ladder, BotGame, created, timestamp ) VALUES ('$game', '$pass', '$desc', '$diff', '$realm', 'lad', '$bot', '$timestamp', '$timestamp')";
if ($conn->query($sql) === TRUE) {
$sqli = "INSERT INTO Players (GameID, Name, timestamp) Values ('".mysqli_insert_id($conn)."', '$charInfo', '$timestamp')";
if ($conn->query($sqli) === TRUE) {
$updateUserQuerry = "UPDATE user SET playerID = '" .mysqli_insert_id($conn). "' where hash = '$hash'";
$conn->query($updateUserQuerry);
echo encrypt(mysqli_insert_id($conn));
} else {
echo "Error: " . $sqli . "\n" . encrypt($conn->error);
}
} else {
echo "Error: " . $sql . "\n" . encrypt($conn->error);
}
}
else
echo encrypt("Banned!");
}
}
}
$conn->close();
}
any suggestion that would fix this problem would be acceptably.

Related

Php transaction not working

Select Queries are working properly but insert commands are not saving data in database, i think that i have not done transaction correctly or it could be roll backing transactions due to improper use of syntax
session_start();
if (isset($_COOKIE['username'])) {
$_SESSION['role'] = $_COOKIE['role'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['rid'] = $_COOKIE['rid'];
}
if (!isset($_SESSION['username'])) {
header('location: login.php');
}
$servername = "localhost";
$username = "johnalla_Mohsin";
$password = "Mohsin1982";
$database = "johnalla_m_billing";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
date_default_timezone_set('Asia/Karachi');
$currentdate = date("Y-m-d");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_COOKIE['username'])) {
$_SESSION['role'] = $_COOKIE['role'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['rid'] = $_COOKIE['rid'];
}
if (isset($_POST['invoice_no'])) {
$conn->autocommit(FALSE);
$result1 = $conn->query("select sum(cost * quantity) as total from temp_entries");
if ($result1->num_rows > 0) {
// output data of each row
while ($row1 = $result1->fetch_assoc()) {
$total = $row1["total"];
}
if ($conn->query("insert into bill (c_name, date, total) values ('$_POST[name]', '$_POST[date]', '$total')") === TRUE) {
$last_id = $conn->insert_id;
$result2 = $conn->query("select * from temp_entries");
if ($result2->num_rows > 0) {
// output data of each row
while ($row2 = $result2->fetch_assoc()) {
$entries[] = $row2;
$conn->query("insert into bill_entries (bill_id, item_name, description, cost, quantity) "
. "values ('$last_id', '$row2[item_name]', '$row2[description]', '$row2[cost]', '$row2[quantity])");
}
if ($conn->query("truncate table temp_entries") === TRUE) {
$conn->commit();
}
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();

want to return the user roleid after successful login

below is my MySQLDao.php
<?php
class MySQLDao {
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $conn = null;
var $dbname = null;
var $result = null;
function __construct() {
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
// function to open connection
public function openConnection() {
$this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno())
echo new Exception("Could not establish connection with database");
}
// function to return the connection
public function getConnection() {
return $this->conn;
}
// function to close the connection
public function closeConnection() {
if ($this->conn != null)
$this->conn->close();
}
// function to get user email
public function getUserDetails($email)
{
$returnValue = array();
$sql = "select * from ap_users where user_email='" . $email . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
// get user details using email and password
public function getUserDetailsWithPassword($email, $userPassword, $roleid)
{
$returnValue = array();
$sql = "select id,user_email from ap_users where user_email='" . $email . "' and user_password='" .$userPassword . "' and user_roleid='" . $roleid . "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
// register user with all fields
public function registerUser($email, $password, $username, $fname, $lname, $mobile, $roleid)
{
$sql = "insert into ap_users set user_email=?, user_password=?, user_username=?, user_fname=?, user_lname=?, user_mobile=?, user_roleid=?";
$statement = $this->conn->prepare($sql);
if (!$statement)
throw new Exception($statement->error);
$statement->bind_param("sssssss", $email, $password, $username, $fname, $lname, $mobile, $roleid);
$returnValue = $statement->execute();
return $returnValue;
}
}
?>
and my UserLogin.php is as under:
<?php
require("Conn.php");
require("MySQLDao.php");
$email = htmlentities($_POST["email"]);
$password = htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetailsWithPassword($email,$secure_password);
if(!empty($userDetails))
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is logged in";
$returnValue["role"] = "'" .$roleid. "'";
echo json_encode($returnValue);
} else {
$returnValue["status"] = "error";
$returnValue["message"] = "User is not found";
echo json_encode($returnValue);
}
$dao->closeConnection();
?>
problem here is when i push the $roleid value always it shows null.
result is like this: {"status":"Success","message":"User is logged in","role:"""}
added MySqlDao getUserDetailsWithPassword() method
$sql = "select id,user_email,user_roleid from ap_users where user_email='" . $email . "' and user_password='" .$userPassword . "' and user_roleid='" . $roleid . "'";
and in user login changed
$returnValue["role"] = "'" .$roleid. "'"; line to $returnValue['user_roleid'] = $userDetails['user_roleid'];
this accomplish my desired result!

You have an error in your SQL syntax, why?

My PHP code.
<?php
$servername = "localhost";
$username = "xxxxxxxxx";
$password = "xxxxxxxxx";
$database = "xxxxxxxxx";
$postdata = file_get_contents("php://input");
$data = json_decode($postdata, true);
$table = $data['table'];
$name = $data['name'];
$email = $data['email'];
$points = $data['points'];
$percentage = $data['percentage'];
$userAnswers = $data['userAnswers'];
function connect_DB($servername, $username, $password, $database) {
$db_conn = new mysqli($servername, $username, $password, $database);
$char = $db_conn->query("SET NAMES 'utf8'");
if ($db_conn->connect_error) {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Connection failed: " . $db_conn->connect_error);
}
else {
echo "Connected successfully \r\n";
}
return $db_conn;
}
function create_DB_table($db, $table) {
$sql = "CREATE TABLE IF NOT EXISTS $table (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
reg_date TIMESTAMP
)";
if ($db->query($sql) == TRUE) {
echo "Table successfully created \r\n";
}
else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Table creation failed: " . $db->error);
}
}
function addColumnVarchar($conn_obj, $table, $column) {
$sql = $conn_obj->prepare("SHOW COLUMNS FROM $table LIKE '%$column%'"); // add wildcard
$sql->execute();
if($sql->num_rows <= 0) {
$sql->store_result();
$sql1 = $conn_obj->prepare("ALTER TABLE $table ADD COLUMN $column VARCHAR(255)");
$sql1->execute();
}
}
function addColumnFloat($conn_obj, $table, $column) {
$sql = $conn_obj->prepare("SHOW COLUMNS FROM $table LIKE '%$column%'"); // add wildcard
$sql->execute();
if($sql->num_rows <= 0) {
$sql->store_result();
$sql1 = $conn_obj->prepare("ALTER TABLE $table ADD COLUMN $column FLOAT");
$sql1->execute();
}
}
function insert_DB($db, $table, $column, $value) {
$sql = "INSERT INTO $table ($column)
VALUES ($value)";
if( $db->query($sql) == TRUE) {
echo "Records inserted successfully!";
}
else {
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die("Records insertion failed: " . $db->error);
}
}
//connect to the database and create table
$conn_obj = connect_DB($servername, $username, $password, $database);
create_DB_table($conn_obj, $table);
$columnArr = array();
$valueArr = array();
if (!is_null($name)){
addColumnVarchar($conn_obj, $table, 'name');
array_push($columnArr, "name");
array_push($valueArr, $name);
}
if (!is_null($email)){
addColumnVarchar($conn_obj, $table, 'email');
array_push($columnArr, "email");
array_push($valueArr, $email);
}
if (!is_null($points)){
addColumnFloat($conn_obj, $table, 'points');
array_push($columnArr, "points");
array_push($valueArr, $points);
}
if (!is_null($percentage)){
addColumnFloat($conn_obj, $table, 'percentage');
array_push($columnArr, "percentage");
array_push($valueArr, $percentage);
}
if (!is_null($userAnswers)){
foreach ($userAnswers as $ua) {
addColumnVarchar($conn_obj, $table, $ua['qID']);
array_push($columnArr, $ua['qID']);
array_push($valueArr, wordwrap($ua['answer'], 60, "\n", false));
}
}
$column = implode(",", $columnArr);
$value = "'".implode("','", $valueArr)."'";
insert_DB($conn_obj, $table, $column, $value);
$conn_obj->close();
The output is:
Connected successfully Table creation failed: 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 '( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, reg_date TIMEST' at line 1
Is there a syntax error?

multi_query() has an error

I need some help finding my error on the enclosed code. When I run either of the two queries using the if ($conn->query($sql) === TRUE) { method each works correctly. But when I try to combine them with the if ($conn->multi_query($sql) === TRUE) { method. No records are uploaded. What am I doing wrong here.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connection made...";
$payload_dump = $_POST['payload'];
echo $payload_dump;
$payload_array = json_decode($payload_dump,true);
if(is_array($payload_array)){
foreach($payload_array as $row){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
$sql = "INSERT INTO data(device, type, zone, sample, count, date_time, epoch_stamp) VALUES('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch');";
$sql . = "UPDATE data SET date_time = FROM_UNIXTIME(epoch_stamp);";
if ($conn->multi_query($sql) === TRUE) {
//if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
... and yes I realize this code is not secure but it's ok for my testing purposes.
Intrinsically the code below is the same until we get to the loop where we build up an array of queries to be executed and execute the multi_query() once at the end once we leave the loop. I have removed some of the comments and statements that echo out info at the start for brevity. I hope this looks ok and works....
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practice";
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) die("Connection failed: " . $conn->connect_error);
$payload_dump = $_POST['payload'];
$payload_array = json_decode($payload_dump,true);
if( is_array( $payload_array ) ){
$queries=array();
foreach( $payload_array as $row ){
//get the data_payload details
$device = $row['device'];
$type = $row['data_type'];
$zone = $row['zone'];
$sample = $row['sample'];
$count = $row['count'];
$time = $row['date_time'];
$epoch = $row['epoch_stamp'];
/*note: we do not need to add the semi-colon here as it gets added later when we implode the array */
$queries[]="INSERT INTO `data` ( `device`, `type`, `zone`, `sample`, `count`, `date_time`, `epoch_stamp` ) VALUES ('$device', '$type', '$zone', '$sample', '$count', '$time', '$epoch')";
}
/*
Previously the below query was being execute on every iteration
~ because $epoch is now the last one encountered in the array,
the value that is updated in ALL records is as it would have been
previously.
*/
$queries[]="UPDATE `data` SET `date_time` = from_unixtime( $epoch );";
$sql=implode( ';', $queries );
if ( $conn->multi_query( $sql ) === TRUE ) {
echo "New records created and updated successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>

PDO not throwing errors

I have the following code to insert a new record in a database:
<?php
require('comune.php');
$nome = $_POST['nome'];
$username = $_POST['username'];
$segreto = $_POST['password'];
$password = md5($segreto);
$validity = $_POST['validity'];
$ruolo = $_POST['ruolo'];
$funzione = $_POST['funzione'];
list($giorno, $mese, $anno) = explode('/', $validity);
$validity = implode('-', array($anno, $mese, $giorno));
try {
$sql = "INSERT into utenti "
. "(nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES ('$nome', '$username', '$segreto', '$password', '$validity', '$ruolo', '$funzione')";
$s = $pdo->prepare($sql);
$s->execute();
} catch (PDOException $e) {
$message = "ko";
}
$message = "ok";
//echo $sql;
echo $message;
?>
The issue I am facing is that, even if the query returns an error, $message is "ok". What am I doing wrong??
change your code to
$sql = "INSERT into utenti (nome,username,segreto,password,validity,ruolo,funzione) "
. "VALUES (?,?,?,?,?,?,?)";
$s = $pdo->prepare($sql);
$s->execute([$nome, $username, $segreto, $password, $validity, $ruolo, $funzione]);
echo "ok";
you will have either ok or informative error message

Categories