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..
}
Related
SO i have been trying with a php project and everything is working fine.Except a bit extra.
Login page redirects to Dashboard even with incorrect details .So basically login is bypassed regardless the login details. Also By putting "sitename/dashboard" directly also bypasses the login. Below Are my Code.
1.index(login page)
<?php
require('inc/dbPlayer.php');
require('inc/sessionManager.php');
$msg="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["btnLogin"])) {
$db = new \dbPlayer\dbPlayer();
$msg = $db->open();
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>HMS</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel-body">
<form name="login" action="index.php" accept-charset="utf-8" method="post" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="E-mail/Login ID" name="email" type="text" autofocus required>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="" required>
</div>
<div class="checkbox">
<label>
<input name="remember" type="checkbox" value="Remember Me">Remember Me
</label>
Forget Password
<label id="loginMsg" class="red"><?php echo $msg ?></label>
</div>
<button type="submit" name="btnLogin" class="btn btn-lg btn-success btn-block"><i class="glyphicon glyphicon-log-in"></i> Login</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
2.dbplayer
<?php
namespace dbPlayer;
class dbPlayer {
private $db_host="localhost";
private $db_name="hms";
private $db_user="root";
private $db_pass="";
protected $con;
public function open(){
$con = mysql_connect($this->db_host,$this->db_user,$this->db_pass);
if($con)
{
$dbSelect = mysql_select_db($this->db_name);
if($dbSelect)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function close()
{
$res=mysql_close($this->con);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
public function insertData($table,$data)
{
$keys = "`" . implode("`, `", array_keys($data)) . "`";
$values = "'" . implode("', '", $data) . "'";
//var_dump("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
mysql_query("INSERT INTO `{$table}` ({$keys}) VALUES ({$values})");
return mysql_insert_id().mysql_error();
}
public function registration($query,$query2)
{
$res=mysql_query($query);
if($res)
{
$res=mysql_query($query2);
if($res)
{
return "true";
}
else
{
return mysql_error();
}
}
else
{
return mysql_error();
}
}
public function getData($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't get data ".mysql_error();
}
else
{
return $res;
}
}
public function update($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't update data ".mysql_error();
}
else
{
return "true";
}
}
public function updateData($table,$conColumn,$conValue,$data)
{
$updates=array();
if (count($data) > 0) {
foreach ($data as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
}
$implodeArray = implode(', ', $updates);
$query ="UPDATE ".$table." SET ".$implodeArray." WHERE ".$conColumn."='".$conValue."'";
//var_dump($query);
$res = mysql_query($query);
if(!$res)
{
return "Can't Update data ".mysql_error();
}
else
{
return "true";
}
}
public function delete($query)
{
$res = mysql_query($query);
// var_dump($query);
if(!$res)
{
return "Can't delete data ".mysql_error();
}
else
{
return "true";
}
}
public function getAutoId($prefix)
{
$uId="";
$q = "select number from auto_id where prefix='".$prefix."';";
$result = $this->getData($q);
$userId=array();
while($row = mysql_fetch_assoc($result))
{
array_push($userId,$row['number']);
}
// var_dump($UserId);
if(strlen($userId[0])>=1)
{
$uId=$prefix."00".$userId[0];
}
elseif(strlen($userId[0])==2)
{
$uId=$prefix."0".$userId[0];
}
else
{
$uId=$prefix.$userId[0];
}
array_push($userId,$uId);
return $userId;
}
public function updateAutoId($value,$prefix)
{
$id =intval($value)+1;
$query="UPDATE auto_id set number=".$id." where prefix='".$prefix."';";
return $this->update($query);
}
public function execNonQuery($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return "true";
}
}
public function execDataTable($query)
{
$res = mysql_query($query);
if(!$res)
{
return "Can't Execute Query".mysql_error();
}
else
{
return $res;
}
}
}
3.Session manager
<?php
namespace sessionManager;
class sessionManager {
public function Set($key,$value)
{
$_SESSION[$key] = $value;
// $_SESSION['start'] = time();
// $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
public function Get($key)
{
// session_start();
if(isset($_SESSION[$key])) {
return $_SESSION[$key];
}
else
{
return null;
}
}
public function isExpired()
{
//session_start();
$now = time();
if ($now > $_SESSION['expire']) {
session_unset();
session_destroy();
return true;
}
else
{
return false;
}
}
public function remove($key)
{
//session_start();
unset($_SESSION[$key]);
}
public function start()
{
session_start();
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
}
}
A few hints:
require values should not be in brackets.
you should NOT be using mysql_ functions, this library is now CEASED and unavailable in PHP 7. Get up to date to 2012 and use mysqli_ or PDO. (Why?)
You should be using PHP 7. As a minimum. (Why?)
Do NOT use md5 for hashing passwords. Use PHP's built in password_hash() function(s). (How?)
STOP outputting errors to screen (aka return mysql_error();). You should be sending errors to an error log (error_log(print_r(mysql_error(),true));) so the public can't see the details of the error.
Read your PHP Error Log. What does it say?
Use Prepared Statements on your database interactions. ([How?(https://phpdelusions.net/mysqli))
Header("Location: ... "); functions should always be immediately followed by exit;/die();
NEVER trust user input. Even if the user tells you it's harmless. (Why?)
Read your PHP Error Log. What does it say?
Your classes should probably have class __constuct() functions. (why?)
You can use Boolean Values instead of strings; use return true; instead of return "true";
You STILL should NOT be using mysql_ functions, Why are you still using them? Stop reading this and update your codebase! Use mysqli_ or PDO. (Why?)
Learn the differences between the different PHP Comparison Operators. And apply what you learn to your code.
Use the PHP Manual to find out and use the multitude of functions available in PHP.
Please get in touch with me if you wish to purchase a copy of PHP 6 (rated 4.5/5 stars on TripAdvisor).
You have a lot of reading to do, and a lot to learn. I would say good luck, but you don't need any luck, you need to read and commit yourself to learning how to use PHP properly.
Have fun.
You need to apply a condition whether you have record in database or not. If not then you need to bypass to login page. Change this code as below:
if ($msg == "true") {
$userPass = md5("hms2015".$_POST['password']);
$loginId = $_POST["email"];
$query = "select loginId,userGroupId,password,name,userId from users where loginId='" . $loginId . "' and password='" . $userPass . "';";
var_dump($query);
$result = $db->getData($query);
//var_dump($result);
if (mysql_num_rows($result) > 0) { // means user is logged in
$info = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($info, $row['loginId']);
array_push($info, $row['userGroupId']);
array_push($info, $row['password']);
array_push($info, $row['name']);
array_push($info, $row['userId']);
}
//$db->close();
$ses = new \sessionManager\sessionManager();
$ses->start();
$ses->Set("loginId", $info[0]);
$ses->Set("userGroupId", $info[1]);
$ses->Set("name", $info[3]);
$ses->Set("userIdLoged", $info[4]);
if (is_null($info[0])) {
$msg = "Login Id or Password Wrong!";
}
else
{
}
if($info[1]=="UG004")
{
header('Location: http://localhost/hms/sdashboard.php');
}
elseif($info[1]=="UG003")
{
header('Location: http://localhost/hms/edashboard.php');
}
else
{
header('Location: http://localhost/hms/dashboard.php');
}
}
}
But I will suggest you to use PDO as mysql is deprecated already. Also your code is widely open for SQL injection as well so read about it as well. Hope it helps you but make your code reliable.
i have problem, on my code i create chat, but duplicate users name, i try prevent but not success.... some can help?
my code:
$sql = "SELECT * FROM `inbox` WHERE `from`='".$_SESSION['username']."' OR `to`='".$_SESSION['username']."' ORDER by `data` DESC;";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
$lastuser = "";
while($row = mysqli_fetch_array($result)) {
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
if($lastuser != $chat_name) {
echo "
<a href='?user=".$chat_name."'>
<div class='inbox_users_box'>
<div class='inbox_imagenuser'>
<img class='inbox_image' src='".getAvatarOthers($chat_name)."'></img>
<div style='margin-top: 14px; float: left;'>".$chat_name."</div><span style='margin-top: 17px; margin-left: 5px;' class='".getonline_player($chat_name)."'></span>
<div style='clear:both;'></div>
</div>
<div class='inbox_lastmsgdata'>".$row['data']."</div>
</div>
<div style='clear:both;'></div>
</a>
";
$lastuser = $chat_name;
}
}
my chat : my chat picture
i want dont duplicate users..
You can save the filtered inbox entries in an array with the data to display, but only when the user isn't already in that array. This way it gets added only once. After that you print the array the way you like with a normal foreach() loop.
$users = array();
while ($row = mysqli_fetch_assoc($result);
// retrieve the data from MySQL
$chat_name = "";
if($row['from'] == $_SESSION['username']) {
$chat_name = $row['to'];
} else {
$chat_name = $row['from'];
}
$data = $row['data'];
// look if the user is already in the array
$found = false;
foreach ($users as $user) {
if ($user['name'] == $chat_name) {
$found = true;
break;
}
}
if ($found) {
continue;
}
// its not, so add it
$toAdd = array('name' => $chat_name, 'data' => $data);
$users[] = $toAdd;
}
/* display users */
foreach ($users as $user) {
$username = $user['name'];
$data = $user['data'];
// your HTML code here
}
I want the table tag to come before the display of records in cart() function but it is being displayed after it rather?
How to correct that and in cart() function in the display of records when I am trying <tr> and <td> tags to display its not working
<?php
session_start();
$page = 'index.php';
$connection = mysqli_connect("localhost","root","","cart");
if(isset($_GET['add']))
{
if(array_key_exists('cart_'.$_GET['add'], $_SESSION))
$_SESSION['cart_'.$_GET['add']]+= 1;
else
$_SESSION['cart_'.$_GET['add']] = 0;
header("Location: cartindex.php");
}
if(isset($_GET['remove']))
{
$_SESSION['cart_'.$_GET['remove']]--;
header("Location: cartindex.php");
}
if(isset($_GET['delete']))
{
$_SESSION['cart_'.$_GET['delete']]=0;;
header("Location: cartindex.php");
}
function cart()
{
global $connection;
$total = 0;
?>
<table class="table table-striped"><tr><th>ID</th><th>Name </th><th>Price Per Item</th><th>Cost</th><th>Add</th><th>Substract</th><th>Delete</th></tr>
<?php foreach ($_SESSION as $key => $value) {
if($value > 0)
{
$id = substr($key,5,strlen($key)-1);
$result = mysqli_query($connection ,'select id,name,price from products where id ='.$id);
while($row = mysqli_fetch_assoc($result))
{
$cost = $row['price'] * $value;
echo $row['id'].' '.$row['name'].'#'.$row['price'].'*'.$value.'='.$cost.'[+]'.'[-]'.'[delete]'.'<br>';
$total = $total + $cost;
}
}
}
?></table><?php
if($total==0)
{
///
}
else
{
$dis="'payment made'";
echo 'Total cost is '.$total.'<br>';
echo '<br><button type="button" class="btn btn-success" onclick="alert(\'Payment accepted\');">Success</button>';
}
}
function product()
{
$connection = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
die("not connected to db ".mysqli_connect_error());
}
$get = mysqli_query($connection , "select id,name,description,price from products where quantity > 0 order by id DESC");
while($row = mysqli_fetch_assoc($get))
{
echo '<div class="boxed">'.$row['name'].'<br>'.$row['price'].'<br>'.$row['description'].'<br>ADD'.'<br>'.'</div>';
}
}
?>
Try replace "echo" with "return" inside functions.
I can upload images as a serialized array no problem, but all I need is to store the raw filename string on my database and I'm not sure where to start editing my pre-existing code get this to work. This should be easier but as a PHP novice I can't get it to work.
Essentially, I want to be able to upload images then display them on the front end of my site doing something like this:
<img src="img/<php echo $config->photo_a ?>"/>
My existing code is:
<?php
//connect to db //
session_start();
include('../config.php');
// check for login to use //
if (!$user->authenticated)
{
header('Location: login.php');
die();
}
//post form as array using class photo_loader//
if (isset($post->form_action))
{
$a = new photo_loader(false, $db);
$a->name = $post->name;
$image_files = array();
for ($i=1; $i<10; $i++)
{
if (isset($_FILES['file'.$i]['name']) && $_FILES['file'.$i]['name'] != "")
{
$img = new upload($_FILES['file'.$i], M_ENV_SITE_URL, M_ENV_SITE_ROOT);
$img->set_upload_target("/img/");
$n = $img->do_upload();
if (!$n)
{
$err = "Image file ".$i." too big or wrong file type.";
}
else
{
$image_files[] = $n;
$img->batchResize("/img/", "/img/", $n, array("320x240", "800x600"));
}
}
}
if (empty($image_files)) $err = "You must include at least one image.";
$a->value = $image_files;
if (!$err)
{
$a->create();
$succ = "Success!";
}
}
?>
Using a simple form like this:
<form action="" method="post" enctype="multipart/form-data">
<div class="control-group"><label for="file" class="control-label">Attach Slideshow Images:</label><div class="controls">
<?php
for ($i=1;$i<10;$i++)
{
echo "<input name=\"file".$i."\" type=\"file\" value=\"\" id=\"file".$i."\" />";
} ?>
</div></div>
<input type="hidden" name="name" value="photo_a">
<div class="form-actions">
<input type="submit" name="form_action" class="btn btn-large btn-primary" value="Save" />
</div>
</form>
and photo_loader.class.php looks like this:
<?php
class photo_loader
{
private $properties;
var $db;
function __construct($id, $dbase)
{
$this->db = $dbase;
if (is_numeric($id))
{
$sql = sprintf(
"SELECT * FROM minty_config
WHERE ID=%d",
$this->db->clean($id)
);
$result = $this->db->query($sql);
$fields = $this->db->fetch_array($result);
foreach ($fields as $k => $v)
{
$this->properties[$k] = $v;
}
$this->value = unserialize($this->value);
}
}
function __get($k)
{
return $this->properties[$k];
}
function __set($k, $v)
{
$this->properties[$k] = $v;
}
function update()
{
$sql = sprintf(
"UPDATE minty_config SET
name='%s',
value='%s'
WHERE ID=%d",
$this->db->clean($this->name),
serialize($this->value),
$this->ID
);
$this->db->query($sql);
}
function create()
{
$sql = sprintf(
"INSERT INTO minty_config
(name, value)
VALUES('%s', '%s')",
$this->db->clean($this->name),
unserialize($this->value)
);
$this->db->query($sql);
}
function delete()
{
$sql = sprintf(
"DELETE FROM minty_config
WHERE ID=%d",
$this->ID
);
$this->db->query($sql);
}
}
?>
I presume I need to remove the $image_files = array(); section but I don't know what to replace with! Seemingly keep making mistakes and returning blank pages with errors or not uploading the image. I can't see it being too diffuclt but I presume I'm going the wrong way about it. Many thanks in advance!!
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.