Checkbox not updating SQL query on button press using PHP - 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

Related

White page PHP data insert

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.

How to insert every value of array variable in database

How to insert every value of array variable in database, whenever i try to insert value using array variable it gives me a error "Array to string conversion".Actually i want to store the attendance of students into "attendance database table", i am retrieving id and name of students from students database, this information of students is being stored in array but when i use array variable"$result" to insert the name of student into attendence_tbl database it gives me error of array to string conversion.
<html>
<head>
</head>
<body>
<div class="container">
<div class="row">
<div class="templatemo-line-header" style="margin-top: 0px;" >
<div class="text-center">
<hr class="team_hr team_hr_left hr_gray"/><span class="span_blog txt_darkgrey txt_orange">Attendance Form</span>
<hr class="team_hr team_hr_right hr_gray" />
</div>
</div>
</div>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");?>
<div class="form-container">
<form method="post" action="" role="form">
<!-- <div class="container"> -->
<div class="col-lg-3">
<div class="form-group">
<?php
$qs=mysql_query("select * from student_table");
?>
<table border=1>
<?php
$c=0;
while($stid=mysql_fetch_row($qs))
{
?>
<tr>
<td ><?php echo $stid[0]?></td>
<td><?php echo $stid[1]?></td>
<td>
<select name="present[]" >
<option value=""> ---Select Attendence--- </option>
<option value="P"> Present </option>
<option value="A"> Absent </option>
</select></td>
</tr>
<?php
$stud= $stid[0];
$subj= $stid[1];
$location_vars = array(/*"stud" ,*/ "subj");
$result[] = compact("nothing_here", $location_vars);
$date = date('Y-m-d H:i:s');
$c++;
}
// echo "</select>"."<br>";
echo $c;
$e=0;
if(isset($_POST['present'])){
foreach($_POST['present'] as $present){
print_r($result);
$query=mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES('$stud','$stid','$present','$date')");
$e++;
}}
?>
</table>
</div>
</div> <!--col-lg-4-->
<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>
</form>
</div> <!--form-container-->
</div><!--container-->
</body>
</html>
Seems you want to put an array variable data directly into table which is supposed to throw error,
Here is the solution.
For adding all value of an array directly into table you have to use first convert array into json and then need to insert it into database. like this..
$resultJson = json_encode($result);
$query = mysql_query("Insert into tbl_attendence (StudentRollNumber,SubjectId,Attendence,Date)VALUES(".$stud.", ".$resultJson.", ".$present.", ".$date.")");
AND if you want to add all array value into database for each value per row separately then you have to make sure run the loop and then insert each value into database for each record.
If I understand you right you want to upload something like this:
Array([1] => '1', [2] => '2')
into a table, which would not work. So you'd have to use JSON to stringify the array. Example:
<?php
$value = 'Some string';
$value2 = 'Some other string';
$values = Array('String 1', 'String 2', 'String 3');
$json_values = json_encode($values);
$mysqli = new mysqli('HOSTNAME', 'USERNAME', 'PASSWORD', 'DATABASE'); // Connecting to SQL Server
// Checking if connection was successfull
if( $mysqli->connect_errno ){
echo 'There was an error connection to the SQL Server<br>';
echo '(' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
exit; // FAIL
}
// Preparing a statement
$stmt = $mysqli->prepare('INSERT into TABLENAME(value, value2, values) VALUES(?, ?, ?)');
// Checking if php prepared the statement successfully
if(!$stmt){
echo 'There was an error preparing the statement!';
exit;
}
if( !$stmt->bind_param('sss', $value, $value2, $json_values) ){
echo 'There was an error binding params to the statement!';
exit;
}
$stmt->execute();
?>
to post arrays into DB I use this approach:
//database connection class
class Database{
// specify your own database credentials
private $host = "YOUR HOST";
private $db_name = "DATABASE NAME";
private $username = "USERNAME";
private $password = "PASSWORD";
public $conn;
// get the database connection
public function getConnection(){ $this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
//model class
class Model{
// database connection
private $conn;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// add info to db
function create($fieldset){
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// query to insert record
$query = "INSERT INTO
tbl_attendence
SET
$fieldset";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}else{
return false;
}
}
}
//part that will handle the post
// get database connection
$database = new Database();
$db = $database->getConnection();
//instatiate model
$model = new Model($db);
//function that will filter posted values
function filter($value){
$value = trim($value);
$value = strip_tags($value);
$value = stripslashes($value);
$value = htmlentities($value);
return $value;
}
if(!empty($_POST)){
//Get Variables
foreach($_POST as $key => $value){
//this part will tackle values which are arrays
if(is_array($value)){
$val=implode(",",filter($value));
$groupVal[] = $val;
$groupKeys[] = $key;
}
else{
$groupVal[] = $this->filter($value);
$groupKeys[] = $key;
}
}
//count items in array to establish a limit
$limit = count($_POST);
//arranges the data into "key = value" format
for($i=0;$i<$limit;$i++){
$prepFieldset[$i] = "$groupKeys[$i] = $groupVal[$i]";
}
//prepares the fieldset to be used in SQL query
$fieldset = implode(",",$prepFieldset);
//process them in the model
$status = $model->create($fieldset);
//show response
if($status == true){
$response = 'Data saved';
}
else{
$response = 'Error when saving data';
}
}

The data is not being inserted on this database? Is there something wrong in the php code or in the db please tell?

this is the database,
DB:
db_newsportal
id int auto_increment primary key, title varchar 255, short_description text, image varchar 255, created_by foreign key tbl_admin references userrname,
created_date datetime, modified_date datetime null, modified_by null
The created by and
This is the php..
<?php
if(isset($_POST['btnSubmit'])){
$errror= array();
$slider= new Slider;
image validation of size is not writtenn because the code becomes too long and and difficult to manage here.
if(!empty($_FILES['sliderimage']['name'])){
$slider->sliderimage= $_FILES['sliderimage']['name'];
move_uploaded_file($_FILES['sliderimage']['tmp_name'], 'images/' . $_FILES['sliderimage']['name']);
}else{
if the image is not uploaded..
$error['image']= "Image required";
}
if the error counts 0 then the create slider function is called which is on slider class...
if(count($error)==0){
$slider->create_slider();
}
}
?>
The slider class...
require_once "class.databases.php";
class Slider extends Database{
public $id, $title, $short_description, $image, $created_date,$created_by, $modified_date, $modified_by;
public function create_slider(){
$this->created_date= date('Y:m:d H:i:s');
#session_start();
The username is receieved from the login pages session and the code becomes long so i didnot want to write the login function as well its class..
$this->created_by = $_SESSION['username'];
$add_info= get_object_vars($this);
$id= $this-> insert_fields('tbl_slider', array_keys($add_info), array_values($add_info));
if($id){
echo "Image Inserted with $id";
}else{
echo "Image Insertion Failed";
}
}
}
?>
This is the Database class....
<?php
class Database{
private $conn;
public function __construct(){
$this->conn= new mysqli ('localhost', 'root', '', 'db_newsproject');
}
public function execute_sql($sql){
$res= $this->conn->query($sql);
$info= array();
if ($res->num_rows >0) {
//print_r($res);
//echo "login Succeess";
while($row=$res->fetch_object()){
array_push($info, $row);
}
}
return $info;
// }
}
function insert_fields($table, $fields, $values){
// // echo $table;
// print_r($fields);
// print_r($values);
$sql= "insert into $table (";
foreach($fields as $field){
$sql= $sql. "$field,";
}
$sql= substr($sql,0, strlen($sql)-1);
//echo $sql;
$sql= $sql . ") values(";
foreach ($values as $value){
$sql= $sql . " '$value',";
}
$sql= substr($sql,0, strlen($sql)-1);
$sql= $sql . ")";
$this->conn->query($sql);
When i try to echo the sql the sql query is not echoed on the slider page.
echo $sql;
if($this->conn->insert_id!=0){
return $this->conn->insert_id;
}else{
return false;
}
}
?>
SO where is the problem..the image is not being inserted.
this is the html
<form action="slider.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Slider Image input</label>
<input type="file" name="sliderimage"> </input>
</div>
<button type="submit" name="btnSubmit" class="btn btnsuccess">Submit</button>
<button type="reset" class="btn btn-danger">Reset </button>
</form>
There was a typo or rather variable misplacement in your code. Where you were supposed to do $slider->image=... You did $slider->sliderimage=... of which public $image and not public $sliderimage was declared on your Slider Class. See the Corrected version of your code below:ยจ
<?php
if(isset($_POST['btnSubmit'])){
$errror = array();
$slider = new Slider;
if(!empty($_FILES['sliderimage']['name'])){
// YOU PROBLEM IS RIGHT HERE... NOT $slider->sliderimage
// RATHER $slider->image AS IT IS IN YOUR SLIDER CLASS
$slider->image = $_FILES['sliderimage']['name'];
move_uploaded_file($_FILES['sliderimage']['tmp_name'], 'images/' . $_FILES['sliderimage']['name']);
}else{
$error['image']= "Image required";
}

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..
}

Difficulty uploading & updating images to directory/MySQL using PHP

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!!

Categories