White page PHP data insert - php

I am looking for answers on Stack Overflow and Google, have read about 50 same questions, every time its different, my head is already boiling. I have a simple PHP CRUD application with OOP.
It has a connection to the database (it works, my data is fetched from the database and I could see it at my index.php in Opera/Safari), has 'add' action (it doesn't work - white page), 'edit' action (it doesn't work - white page), 'delete' action (it works).
UPDATE2:
I have changed cli interpreter to 5.6. Now I see some errors (if I add this line to .ini file 'always_populate_raw_post_data' to '-1' errors are disappear, but I see a white page again):
Deprecated: Automatically populating $HTTP_RAW_POST_DATA is .
deprecated and will be removed in a future version. To avoid this
warning set 'always_populate_raw_post_data' to '-1' in php.ini and
use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in
Unknown on line 0
Array ( [type] => 2 [message] => Cannot modify header information -
headers already sent [file] => Unknown [line] => 0 ) Array ( [type]
=> 2 [message] => Cannot modify header information - headers already
sent [file] => Unknown [line] => 0 )
I am using in my project:
PHPSTORM
PHP CLI interpreter 7.2
PHP version 5.6
add.php code:
<html>
<head>
<title>Add Data</title>
</head>
<body>
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg != null) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
}
else {
$result = $crud->execute("INSERT INTO users(name,age,email) VALUES('$name','$age','$email')");
echo "<p style='color=green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}?>
</body>
</html>
edit.php
<?php
include_once("classes/Crud.php");
$crud = new Crud();
$id = $crud->escape_string($_GET['id']);
$result = $crud->getData("SELECT * FROM users WHERE id=$id");
foreach ($result as $res) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="editaction.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo
$name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo
$age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo
$email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo
$_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update">
</td>
</tr>
</table>
</form>
</body>
</html>
editaction.php
<?php
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['update']))
{
$id = $crud->escape_string($_POST['id']);
$name = $crud->escape_string($_POST['name']);
$age = $crud->escape_string($_POST['age']);
$email = $crud->escape_string($_POST['email']);
$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
$check_age = $validation->is_age_valid($_POST['age']);
$check_email = $validation->is_email_valid($_POST['email']);
if($msg) {
echo $msg;
echo "<br/><a href='javascript:self.history.back();'>Go
Back</a>";
} elseif (!$check_age) {
echo 'Please provide proper age.';
} elseif (!$check_email) {
echo 'Please provide proper email.';
} else {
$result = $crud->execute("UPDATE users SET
name='$name',age='$age',email='$email' WHERE id=$id");
header("Location: index.php");
}
}
?>
DB SCHEME:
create database test;
use test;
CREATE TABLE `users` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(100) NOT NULL,
`age` int(3) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
);
Crud.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'DbConfig.php';
class Crud extends DbConfig
{
public function __construct()
{
parent::__construct();
}
public function getData($query)
{
$result = $this->connection->query($query);
if ($result == false) {
return false;
}
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function execute($query)
{
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot execute the command';
return false;
} else {
return true;
}
}
public function delete($id, $table)
{
$query = "DELETE FROM $table WHERE id = $id";
$result = $this->connection->query($query);
if ($result == false) {
echo 'Error: cannot delete id ' . $id . ' from table ' . $table;
return false;
} else {
return true;
}
}
public function escape_string($value)
{
return $this->connection->real_escape_string($value);
}
}
?>

The problem was with phpStorm. My app won't work with PHP interpreter running inside phpStorm.
I run my app in Apache2 HTTP server and it works well.

Related

Checkbox not updating SQL query on button press using PHP

With this code, it can retrieve the values from the database with a checkbox on each row. What I want for it to do is to update the unchecked values (namely 0) in the database with 1 for each checkbox checked.
Here's the query for the database and some sample rows.
CREATE TABLE IF NOT EXISTS `job_order` (
`ID` int(255) NOT NULL AUTO_INCREMENT,
`SI_no` varchar(12) NOT NULL DEFAULT '1',
`Date_Issued` date NOT NULL,
`Date_completed` date DEFAULT NULL,
`checked` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
INSERT INTO `job_order` (`ID`, `SI_no`, `Date_Issued`, `Date_completed`,
`checked`) VALUES
(1, '2', '2018-12-19', '2018-12-26', 1),
(2, '5', '2018-11-06', '2018-12-04', 1),
(3, '7', '2018-12-01', '2018-12-13', 0),
(4, '8', '2018-12-20', '2018-12-12', 0);
COMMIT;
db_c.php - the class file
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($order['order-complete'])){
foreach($order['order-complete'] as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
I'm mostly having problems with the function complete_orders, which doesn't return anything on button press of the submit button. Nor does it check if the checkboxes are ticked.
Here's the HTML layout file
jobrequestfilter.php
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
The isset button returns the echo statement I put, however, most seems to be working fine except for the process order button. Is it wise to just use javascript for the checkbox on update?
Try this one
db_c.php
It should not be
$order['order-complete']
But
$orders
Because the array variable name from post already stored in variable $orders.
It should not be
$id
But
$ids
Because you declare it as
foreach($orders as $ids)
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'your_db_name' );
class db_c{
public $mysqli;
function __construct() {
$this->mysqli = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if(!$this->mysqli){
die('Could not Connect My Sql:' .mysql_error());
}
}
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders)){
foreach($orders as $ids){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `id` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $ids);
if($stmt->execute()){
array_push($processed, $ids);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
function return_orders(){
$orders = array();
$sql = "SELECT `ID`, `SI_no`, `date_issued`, `date_completed`, `checked` FROM `job_order` WHERE `checked` != 1";
if($stmt = $this->mysqli->prepare($sql)){
if($stmt->execute()){
$stmt->bind_result($ID, $SI_no, $date_issued, $date_completed, $checked);
$stmt->store_result();
while($stmt->fetch()){
$orders[$ID]['SI_no'] = $SI_no;
$orders[$ID]['Issued'] = $date_issued;
$orders[$ID]['Completed'] = $date_completed;
$orders[$ID]['Checked'] = $checked;
}
return $orders;
}else{
return 1;
// failed to execute
}
}else{
return 0;
// failed to prepare
}
}
function orders_2_table(){
$unchecked = $this->return_orders();
if(is_array($unchecked) && !empty($unchecked)){
//returned results, build rows
$table = '';
foreach($unchecked as $id => $dets){
$table .= '<tr><td>'.$dets['SI_no'].'</td><td>'.$dets['Issued'].'</td><td>'.$dets['Completed'].'</td><td><input type="checkbox" name="order-complete[]" value="'.$id.'" /></td></tr>';
}
return array('Rows'=>$table, 'Count'=>count($unchecked));
}elseif(!is_array($unchecked)){
if($unchecked === 0){
return array('Rows'=>'<tr><td colspan="3">Error (SQL) </td></tr>', 'Count'=>0);
}else{
return array('Rows'=>'<tr><td colspan="3">Error (EXE) </td></tr>', 'Count'=>0);
}
}else{
return array('Rows'=>'<tr><td colspan="3">All Orders Completed </td></tr>', 'Count'=>0);
}
}
}
?>
jobrequestfilter.php
3.It should not
if(isset($_POST) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST);
It should be
if(isset($_POST['order-complete']) &&
isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
<?php
session_start();
include 'db_c.php';
$dbc = new db_c();
$msg = '';
if(isset($_POST['order-complete']) && isset($_POST['process_orders'])){
$process = $dbc->complete_orders($_POST['order-complete']);
if(is_array($process) && !empty($process)){
$msg = '<tr><td colspan="3">Successfully Processed '.count($process).' Orders</td></tr>';
}
else{
echo '<script>console.log("Nothing processed at jobrequestfilter")</script>';
}
}
$data = $dbc->orders_2_table();
?>
<html>
<head>
<meta charset="utf-8">
<title>Job Request Chart</title>
</head>
<body>
<div id="navbar">
<div id ="wrap">
<div class="logo"></div>
<img id="b" class="b">
</div>
</div>
<form action="" method="post">
<div id="filterby">
<input type="submit" id="Email" class="requestbutton" name="Email" value="Email">
</div>
</form>
<form method="post" enctype="multipart/form-data">
<table id ="jobtable">
<tr><th>SI no.</th><th>Date Issued</th><th>Date Started </th><th>Approve?</th></tr>
<?php echo $msg ?>
<?php echo $data['Rows'] ?>
<tr><td colspan="2"><input type="submit" name="process_orders" value="Process Orders" /></td><td>Count:<?php echo $data['Count'] ?></td></tr>
</table>
</form>
</body>
</html>
Please replace below complete_orders function code
function complete_orders($orders){
$processed = array();
if(is_array($orders) && !empty($orders)){
if(isset($orders['order-complete'])){
foreach($orders['order-complete'] as $id){
$sql = "UPDATE `job_order` SET `checked`= 1 WHERE `ID` = ?";
if($stmt = $this->mysqli->prepare($sql)){
$stmt->bind_param("i", $id);
if($stmt->execute()){
array_push($processed, $id);
}
}
}
return $processed;
}else{
echo '<script>console.log("Nothing returned line 32")</script>';
return 0; //No orders selected
}
}else{
echo '<script>console.log("Nothing processed")</script>';
return 0; //Nothing to process
}
}
Two problem in code:
Function argument $orders you are passing but while process you using order. So it's was not going inside into loop
in foreach iteration your are using ids but while updating query you using id. so change variable accordingly. Please check

Data not being saved in my database

I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}

Mysql INSERT statement FAILING when POSTING large array

I've been searching the internet and "pulling my hair out" for days over this. It works fine on my XAMPP localhost and was working fine on my online testing server until I updated the PHP version and had to rewrite the code due to deprecated syntax.
Basically, I'm making a backend database for photography clients. One of the tables is designed to store image information. I haven't tried to store an actual image (BLOB of some sorts), I'm just looking to store "what and where".
What seems to be happening is if I try entering the contents of a shoot directory with several hundred images, when I hit input the screen changes, then instead of telling me how many were entered, it goes to a "418 unused" page saying
The server encountered an internal error or misconfiguration and was unable to complete your request.
I've been trying to narrow down which buffers to increase or variables like "max_allowed_packet", "max_input_vars"... still no luck. I've even tried comparing the phpinfo between the two servers to find out why one works and the other doesn't...
Here's what I'm doing... the listpage
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
$database = new Database();
$db = $database->getConnection();
$colname_chk_Images = "-1";
if (isset($_GET['ShootId'])) {
$colname_chk_Images = $_GET['ShootId'];
}
$colname1_chk_Images = "NULL";
if (isset($_GET['ShootFolder'])) {
$colname1_chk_Images = $_GET['ShootFolder'];
}
$colname_get_Images = "-1";
if (isset($_SESSION['cID'])) {
$colname_get_Images = $_SESSION['cID'];
}
$entered=0; //check for already entered images
?>
<?php
$dirname=$_SESSION['cIFolder'];
$Clogin=$_SESSION['Clogin'];
$ClientID=$_SESSION['cID'];
$_SESSION['CURR_CLIENT_ID'] = $ClientID;
$maindir=$_GET['ShootFolder'];
$ShootId=$_GET['ShootId'];
$dir=$_SERVER['DOCUMENT_ROOT'].dirname($_SERVER['PHP_SELF'])."protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$_SESSION['dir']=$dir;
$dir2="/protect/clientfolders/".$Clogin."/users/".$Clogin."/images/".$maindir;
$dirt= "/phpThumb-master/";
$dirn= dirname($_SERVER['PHP_SELF']);
$filesArray=array_map('basename', glob($dir."/*.jpg"));
$lightbox_data= "FPAD_Lightbox";
$thumb = "$dir2/";
$notThumb = "$dir2/";
$ic = count($filesArray);
$_SESSION['SESS_TOTNUM'] = $ic;
$_SESSION['sID'] = $ShootId;
$sID = $_SESSION['sID'];
include_once 'header_a.php';
?>
<div class="container">
<?php
echo $_SESSION['SESS_TOTNUM']." images found ";
echo "for Shoot ID#: ".$_SESSION['sID']."<br>";
echo "*Note* - if input boxes come up GREEN, then images are already loaded into the database";
?>
<p>
<?php
$images1 = new Image($db);
$images1->ShootId = $colname_chk_Images;
$images1->directory = $colname1_chk_Images;
$images1->ClientID = $colname_get_Images;
$chk_Images = $images1->checkImages();
$get_Images = $images1->getImages();
$Images = array();
while ($row_get_Images = $get_Images->fetch(PDO::FETCH_ASSOC))
{
$Images[] = $row_get_Images['image_name'];
}
?></p>
<form method="POST" name="form1" id="form1" action="input.php">
<table id="clientshoots" class="table table-condensed table-bordered table-small">
<tr>
<th>image_id</th>
<th>image_name</th>
<th>image_path</th>
<th>image_path_root</th>
<th>image_size</th>
<th>directory</th>
<th width="auto">ShootId</th>
<th width="auto">ClientID</th>
<th>ClientName</th>
<th>login</th>
</tr>
<?php $ic=0;
for($i=0;$i<count($filesArray);$i++) {
$fileinfo = $filesArray[$i];
$fname=$dir."/".$fileinfo;
$fname2=$dir2."/".$fileinfo;
$size = filesize($fname);
$atime = date("F d, Y H:i:s", fileatime($fname));
$mtime= date("F d, Y H:i:s", filemtime($fname));
$perms=decoct(fileperms($fname) & 0777);
$type=filetype($fname);
$pth=realpath($fname);
$name=basename($fname);
$dn=dirname($fname2);
if (in_array($fileinfo, $Images)) {
$entered=1;
echo "<style type=\"text/css\">\n";
echo "input {\n";
echo "background-color:#00FF33;\n";
echo "}\n";
echo "</style>";
}
?>
<tr>
<td> </td>
<td><input type="text" name="image_name[]" value="<?php echo $fileinfo; ?>" readonly/></td>
<td><input type="text" name="image_path[]" value="<?php echo $dir; ?>" readonly/></td>
<td><input type="text" name="image_path_root[]" value="<?php echo $dir2; ?>" readonly/></td>
<td><input type="number" name="image_size[]" value="<?php echo $size; ?>" readonly/></td>
<td><input type="text" name="directory[]" value="<?php echo $maindir; ?>" readonly/></td>
<td><input type="number" name="ShootId[]" value="<?php echo $ShootId; ?>" readonly/></td>
<td><input type="number" name="ClientID[]" value="<?php echo $ClientID; ?>" readonly/></td>
<td><input type="text" name="ClientName[]" value="<?php echo $_SESSION['cName']; ?>" readonly/></td>
<td><input type="text" name="login[]" value="<?php echo $Clogin; ?>" readonly/></td>
</tr>
<?php next($filesArray);
$ic=$ic+1;
}
$_SESSION['SESS_IC'] = $ic;?>
</table>
<?php if ($entered == 1){
echo "Return";
} else {
echo "<input class=\"btn-primary\" style=\"background-color:\" id=\"Insert records\" type=\"submit\" value=\"Insert records\">";
}?>
<input type="hidden" name="MM_insert" value="form1">
<input type="hidden" name="sID" value="<?php echo $sID; ?>">
</form>
</div>
<br>
<!-- /container -->
<?php include 'footer_b.php'; ?>
and then the input.php page...
<?php
// set page headers
$page_title = "Enter Images into Database";
include_once 'auth.php';
// get database connection
include_once 'config/fpaddb.php';
include_once 'objects/clients.php';
include_once 'objects/photoshoots.php';
include_once 'objects/images.php';
include_once 'objects/ratings.php';
$database = new Database();
$db = $database->getConnection();
$sID = $_SESSION['sID'];
$ic = $_SESSION['SESS_IC'];
$ma = $_SESSION['SESS_CLIENT_MULTI'];
$gn = $_SESSION['SESS_CLIENT_GRPNO'];
$cID = $_SESSION['cID'];
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
$image1 = new Image($db);
$count = count($_POST['image_name']);
$fileinfo = clean($_POST['image_name']);
//Check for duplicates
if($fileinfo != '') {
for($i=0;$i<$count;$i++) {
$fileinfo = clean($_POST['image_name'][$i]);
//echo $fileinfo;
$image1->image_name = $fileinfo;
$result = $image1->check4Dup();
if($result) {
if(count($result) > 0) {
$errmsg_arr[] = 'Image already entered into Database';
$errflag = true;
}
$result = NULL;
}
else {
die($e->getMessage());
}
next($count);
}
}
$image1->ic = $ic;
$num = $image1->create();
$colname_newImages = "-1";
if (isset($sID)) {
$colname_newImages = $sID;
}
$image1->ShootId = $sID;
$newImages = $image1->countOneShoot();
$row_newImages = $newImages->fetch(PDO::FETCH_ASSOC);
$totalRows_newImages = $newImages->rowCount();
$ic2 = $totalRows_newImages;
$_SESSION['SESS_TOTNUM_ENT'] = $ic2;
header("Location: rs_images.php");
include_once 'header_a.php';
?>
<div class="container">
<?php
echo "Success! Number of images entered is ".$ic2; ?>
<br><br>
<p><input name="Verify" type="button" value="Verify Inputs" onclick="MM_goToURL('parent','rs_images.php');return document.MM_returnValue"/></p>
</div>
<?php include 'footer_b.php'; ?>
And the Class file...
<?php
class Image{
// database connection and table name
private $dbh;
private $table_name = "images";
// object properties
public $image_id;
public $image_name;
public $image_path;
public $image_path_root;
public $image_size;
public $directory;
public $ShootId;
public $ClientID;
public $ClientName;
public $login;
public $ic;
public function __construct($db){
$this->dbh = $db;
}
// Clean Function
function clean($str){
$str = filter_var(($str), FILTER_SANITIZE_STRING);
return ($str);
}
// test function
function test(){
$ic = $this->ic;
$i=1;
$j=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
$Clogin = $login."');";
$i=$i+1;
$j=$j+1;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$Clogin;
//$stmt = $this->dbh->prepare($qry1st.$sql_array);
//$stmt->execute();
echo $qry1st.$sql_array;
}
}
// create function
function create(){
$ic = $this->ic;
$qry1st = "INSERT INTO `images` (image_name, image_path, image_path_root, image_size, directory, ShootId, ClientID, ClientName, login) VALUES ";
$sql_array = array(); // This is where we'll queue up the rows
$queue_num = 50; // How many rows should be queued at once?
$i=1;
foreach ($_POST['image_name'] as $row=>$iname)
{
$image_name = clean($iname);
$image_path = clean($_POST['image_path'][$row]);
$image_path_root = clean($_POST['image_path_root'][$row]);
$image_size = clean($_POST['image_size'][$row]);
$directory = clean($_POST['directory'][$row]);
$ShootId = clean($_POST['ShootId'][$row]);
$ClientID = clean($_POST['ClientID'][$row]);
$ClientName = clean($_POST['ClientName'][$row]);
$login = clean($_POST['login'][$row]);
if ($i==($_SESSION['SESS_TOTNUM'])) {
$login_term = $login."');";
}
else
{
$login_term = $login."')";
$i=$i+1;
}
$sql_array[] = "('".$image_name."', '".$image_path."', '".$image_path_root."', ".$image_size.", '".$directory."', ".$ShootId.", ".$ClientID.", '".$ClientName."', '".$login_term;
// Add a new entry to the queue
$c=0;
if (count($sql_array) >= $queue_num)
{ // Reached the queue limit
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array)); // Insert those that are queued up
$addImages->execute();
$sql_array = array(); // Erase the queue
}//End if
}//end foreach
if (count($sql_array) > 0) // There are rows left over
{
$addImages = $this->dbh->query($qry1st . implode(', ', $sql_array));
$addImages->execute();
}
}
function checkImages(){
$query_chk_Images = "SELECT images.image_name FROM images WHERE ShootId = ? AND directory = ?";
$chk_Images = $this->dbh->prepare ($query_chk_Images);
$chk_Images->bindValue(1, $this->ShootId);
$chk_Images->bindValue(2, $this->directory);
$chk_Images->execute();
return $chk_Images;
}
// create function
function getImages(){
$query_get_Images = "SELECT * FROM images WHERE ClientID = ? ORDER BY image_name ASC";
$get_Images = $this->dbh->prepare ($query_get_Images);
$get_Images->bindValue(1, $this->ClientID);
$get_Images->execute();
return $get_Images;
}
// create function
function getImageID(){
$query_rsImageID = "SELECT * FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$rsImageID = $this->dbh->prepare($query_rsImageID);
$rsImageID->bindValue(1, $this->ShootId);
$rsImageID->execute();
return $rsImageID;
}
// create function
function get_image_id(){
$q = "SELECT image_id FROM images WHERE ShootId = ? ORDER BY image_id ASC";
$stmt = $this->dbh->prepare($q);
$stmt->bindValue(1, $this->ShootId);
$stmt->execute();
return $stmt;
}
// create function
function countOneShoot(){
$query_newImages = "SELECT * FROM images WHERE ShootId = ?";
$newImages = $this->dbh->prepare($query_newImages);
$newImages->bindValue(1, $this->ShootId);
$newImages->execute();
return $newImages;
}
// create function
function check4Dup(){
$qry = "SELECT * FROM `images` WHERE image_name = ?";
$result = $this->dbh->prepare($qry);
$result->bindValue(1, $this->image_name);
$result->execute();
return $result;
}
}
I've striped out all the extra stuff I've tried, like entering the info one record at a time, binding the Values with colon prefixed field names instead of the ?'s. I've tried different loops. I think it comes down to trying to push too much through one query... but then why does it work on XAMPP and why was it working fine with PHP 5.2?
I appreciate any light that can be shed on this. This is my first ever post with regards to PHP, MySQL or anything site related, I've been learning this stuff as I go and had it 90% completed and debugged and when I put it online to do some real testing with the actual directories and client folders that's when I found out that between PHP 5.4 and 5.2, there have been a number of changes and I found myself rewriting almost every line to move up to either MySQLi or PDO/OOP. After doing a lot searching around the internet I've opted for the OOP approach and still need to rewrite even more of the code above to clean things up a ton, but right now I'm troubleshooting the INSERT failure which I have not been able to solve on my own or with the help of all the forums, posts and blogs I've read to date.

Calling functions which are defined in other php file wont work the way I want

I have followin PHP code, it is where I defined my functions:
<?php
function emaili_pikkus($email){
if (strlen($email)>45){
echo 'e-mail ei tohi olla pikem kui 45 tähemärki';
}
else{
$emaili_pikkus=True;
}
}
function parooli_pikkus($parool)
{
$pikkus = strlen($parool);
if ($pikkus<6){
echo "Parool peab olema vähemalt 6 tähemärki pikk";
}
else {
$parooli_pikkus=True;
}
}
function varasem_olemasolu($email)
{
if(!empty($_POST['email']))
{
$query = mysql_query("SELECT * FROM kasutajad WHERE e_mail = '$email'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
$varasem_olemasolu=True;
}
else
{
echo "Selle e-mailiga on kasutaja juba registreeritud.";
}
}
}
function paroolide_kattuvus($parool, $parool_uuesti)
{
if($parool==$parool_uuesti)
{
$paroolide_kattuvus=True;
}
else{
echo "Paroolid ei kattu.";
}
}
function NewUser()
{
global $sql;
if (mysql_query( $sql))
{
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Praks/templates/registreeritud.php'>";
}
}
?>
Then I have other PHP code where I call necessary functions(They are seperated, because I want to use my functions in other applications too):
<meta charset="UTF-8">
<?php
include_once 'init/init.funcs.php';
$email = mysql_real_escape_string($_POST['email']);
$eesnimi = mysql_real_escape_string($_POST['eesnimi']);
$perekonnanimi = mysql_real_escape_string($_POST['perekonnanimi']);
$parool = $_POST['parool'];
$parool_uuesti = $_POST['parooluuesti'];
$salt = rand(10000,99999);
$hashed_pwd = sha1($parool.$salt);
$sql="INSERT INTO kasutajad (e_mail, eesnimi, perenimi, parool, salt ) VALUES ('$email','$eesnimi','$perekonnanimi','$hashed_pwd','$salt')";
emaili_pikkus($email);
if ($emaili_pikkus=True){
parooli_pikkus($parool);
}
if ($parooli_pikkus=True){
varasem_olemasolu($email);
}
if ($varasem_olemasolu=True){
paroolide_kattuvus($parool, $parool_uuesti);
}
if ($paroolide_kattuvus=True){
NewUser();
}
?>
And then I have my HTML code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>Registreerimine</title>
</head>
<body>
<strong>Registreerimiseks täida järgnevad väljad: </strong><br>
<br>
<form method="POST" action="registreerimine4.php">
<table>
<tr><td>Sinu Tieto e-maili aadress: </td><td><input type="text" name="email"></td></tr>
<tr><td>Eesnimi: </td><td><input type="text" name="eesnimi"></td></tr>
<tr><td>Perekonnanimi: </td><td><input type="text" name="perekonnanimi"></td></tr>
<tr><td>Parool: </td><td><input type="text" name="parool"></td></tr>
<tr><td>Parool uuesti: </td><td><input type="text" name="parooluuesti"></td></tr>
</table>
<br>
<input type="submit" value="Registreeri" name="Registreeri">
</form>
</body>
</html>
init.funcs.php looks like that:
<?php
session_start ();
$db = mysql_connect ( 'localhost', 'root', 'aaaa' );
if (! $db) {
header ( "location: /" );
die ();
} else {
mysql_select_db ( 'ta2014' );
}
include_once 'functions/user.funcs.php';
include_once 'functions/survey.funcs.php';
?>
It all together should be a registration form and it worked before I made few changes. Before those changes I had my functions defined to work only for this registration form and they had no parameters needed. Also they were nested in each other. My question is how should I write my second PHP code, so it all would work. Right now it creates new user even if some previous condition are not True. It is a long question and I would be very thankful if someone answers me.
You have a lot of errors in your code:
Your functions aren't returning any value. Variables intitalized inside the function will not be available outside it. The best way is to return a boolean value and check that outside
The function definition:
function some_func($param1, $param2) {
if (some_condition) {
// If everything okay, return TRUE
return TRUE;
} else {
// It's not gonna work with this, so return FALSE
return FALSE;
}
}
Checking the return value:
if (some_func($foo, $bar)) {
// some_func returned TRUE, do further processing
}
With if($var = True), you're not actually checking if a variable is true or not. You're assigning it the boolean value True. You need to write if($var == True instead.
You're using the deprecated mysql_* functions. They're deprecated. Use MySQLi or PDO instead.

php login mysql query reloads login page (MAMP)

I have read most solutions to this where in logging in keeps reloading the login page, but it still doesn't work for me. I tried logging in different browsers (sadly there's only safari and firefox here). There are no errors even if I type no username or password although there is an errorStr in the codes which prints out errors. It just keeps reloading no matter what.
I am a beginner at php programming and I am trying to access an old php website.
Here is the myfunctions.php where in the sql server is connected.
class mysql_db
{
function openCityPassSQL()
{
$dbhostname="localhost:8889";
$dbusername="root";
$dbpassword="root";
$dbname="ticketing";
MYSQL_CONNECT($dbhostname,$dbusername,$dbpassword) OR DIE("Unable to connect to database...");
#mysql_select_db("$dbname") or die("Unable to select database..."); }
function executeQuery($query)
{
return MYSQL_QUERY($query);
}
function executeUpdate($query)
{
return MYSQL_QUERY($query);
}
function numRows($result)
{
return MYSQL_NUM_ROWS($result);
}
function fetchRow($result)
{
return mysql_fetch_array($result);
}
function closeSQL()
{
MYSQL_CLOSE();
}
}
here is my index.php
<?
ini_set('display_errors','1');
$found_msisdn = false;
$temp = $HTTP_COOKIE_VARS["User-Identity-Forward-msisdn"];
if (($temp != null) && ($temp != "")) {
$len = strlen($temp);
$msisdn = "+";
for ($i=0;$i<$len;$i++) {
if (($i % 2) == 1)
$msisdn = $msisdn . $temp[$i];
}
$found_msisdn = true;
}
if (!$found_msisdn) {
//get SMART's MSISDN
$network = $HTTP_SERVER_VARS["HTTP_X_NETWORK_INFO"];
//GPRS,639218025160,515031808225161,10.155.9.87,unsecured
$info = explode(",", $network);
$msisdn = $info[1];
if (($msisdn != null) && ($msisdn != "")) {
$msisdn = "+" . $msisdn;
$found_msisdn = true;
}
}
if ($found_msisdn) {
$msisdn = urlencode($msisdn);
}
if (preg_match("/vnd.wap.wml/",$_SERVER['HTTP_ACCEPT'])){
header("Location: http://wap.surfshop.net.ph/citypass/index.wml?msisdn=$msisdn");
exit;
}
require ("myfunctions.php");
session_start();
$_showform=true;
$errorStr="";
$_username="";
$_password="";
$conn=new mysql_db();
$conn->openCityPassSQL();
if (isSet($a_exit) && $a_exit=="1")
{
session_unregister("verified_user");
$_showform=false;
header("Location: index.php");
}
if (isSet($submitform))
{
$_username=$username;
$_password=$password;
//if (!nameIsValid($_username)) $errorStr=$errorStr.($errorStr!=""?"<br>":"")."Invalid User ID.";
//if (empty($_password) || !passwordIsValid($_password)) $errorStr=$errorStr.($errorStr!=""?"<br>":"")."Invalid Password.";
if (empty($_username)) {
$errorStr = "Invalid username<br>";
}
if (empty($_password)) {
$errorStr .= "Invalid password<br>";
}
if (empty($errorStr))
{
$tid = 0;
$query="SELECT Password, PASSWORD('$password') FROM tblUser WHERE UserID='$_username'";
//echo "query:$query<br>";
$result=$conn->executeQuery($query);
$numRows=$conn->numRows($result);
if ($result && $numRows>0) {
$RS=mysql_fetch_array($result);
$pass1=$RS[0];
$pass2=$RS[1];
if ($pass1 == $pass2) {
$query = "SELECT EstabID FROM tblEstabUser WHERE UserID='$_username'";
$result=$conn->executeQuery($query);
$RS=mysql_fetch_array($result);
$tid = $RS[0];
$admin = false;
$query = "SELECT UserID FROM tblAdminUser WHERE UserID='$_username'";
//echo "query:$query<br>";
$result=$conn->executeQuery($query);
$numRows=$conn->numRows($result);
if ($numRows > 0) {
$admin = true;
$tid = $numRows[1]; //initialize to a value for links to work
}
$verified_user = array($_username, $tid, ($admin?"1":"0"));
session_register("verified_user");
$errorStr = "Welcome $_username!<br>";
$_showform = false;
header("Location: index2.php");
}
else {
$errorStr = "Invalid username/password (PA)<br>";
}
}
else {
$errorStr = "Invalid username/password (NR)<br>";
}
}
}
index2.php
session_start();
$_showform=true;
if (!session_is_registered("verified_user"))
{
$_showform=false;
header("Location: index.php");
}
else
{
list($username,$estabid,$admin)=$verified_user;
if (empty($username))
{
$_showform=false;
header("Location: index.php");
}
}
if ($_showform)
{
?>
<html>
<head>
<title><?=$applicationName?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<?include("header.php");?>
</td>
</tr>
<?
//if ($errorStr!="")
if ($username!="")
{
?>
<tr>
</tr>
<tr>
<td><font face="Verdana" size="2"> </font></td>
</tr>
<?
}
?>
<tr>
<td>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="top">
<?include("menu_in.php");?>
</td>
<td valign="top">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<?
}
?>
I don't really know what the error is, but my guess is the script is just old and my MAMP can't process the query?
I'm just an intern and any help would be appreciated.
These are the following errors I have encountered:
Notice: Undefined index: User-Identity-Forward-msisdn in
/Applications/MAMP/htdocs/ticketing/index.php on line 6
Notice: Undefined index: HTTP_X_NETWORK_INFO in
/Applications/MAMP/htdocs/ticketing/index.php on line 21
Notice: Undefined offset: 1 in
/Applications/MAMP/htdocs/ticketing/index.php on line 26
Warning: session_start() [function.session-start]: Cannot send session
cache limiter - headers already sent (output started at
/Applications/MAMP/htdocs/ticketing/index.php:6) in
/Applications/MAMP/htdocs/ticketing/index.php on line 45
The error information which you have provided clearly shows that
$HTTP_COOKIE_VARS["User-Identity-Forward-msisdn"];
$HTTP_SERVER_VARS["HTTP_X_NETWORK_INFO"];
are completely empty.
Please use
print_r($HTTP_COOKIE_VARS);
print_r($HTTP_SERVER_VARS);
to check for whether the values exists or not.
If there are values in these arrays then your third problem
Notice: Undefined offset: 1 in /Applications/MAMP/htdocs/ticketing/index.php on line 26
will be solved automatically.
on which page it redirects do you know?
Note: SELECT UserID FROM tblAdminUser WHERE UserID='$_username' (i know its not relevant but is USERID col belongs to username?)

Categories