Mysql INSERT statement FAILING when POSTING large array - php

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.

Related

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

How create a table at runtime in MySQL and save it into database

I created a form which creates table with entered number of rows and columns on form. I want to create that entered fields table into database and save its values into database Table. Guide me what I should use.
My code:
<?php
global $Host;
global $Username;
global $password;
global $database;
function getConnection()
{
$Host = "localhost";
$Username = "root";
$password = "";
$database = "labdata";
$oMysqli = new mysqli($Host,$Username,$password,$database);
return($oMysqli);
}
?>
<html>
<head>
<title>aa</title>
</head>
<body>
<form name="report Creation" method="post">
<label for='Table'>Define Table</label>
<label for='column'>Row</label>
<input type="text" name="column"></input>
<label for='rows'>Column</label>
<input type="text" name="rows"></input>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
function displayData($column,$rows)
{
echo "<table border='1' align='center'>";
for($i = 0;$i<$_POST['column'];$i++)
{
echo "<tr>".$i."</tr>";
for($j = 0; $j <$_POST['rows'];$j++)
{
echo "<td>" ."<input type=\"text\" name='column_$i[$j]'>"."</td>";
}
}
echo "</table>";
echo "<form>";
echo "<input type=\"submit\" name=\"ok\" value=\"ok\">";
echo "</form>";
//function displaydata($column = NULL) {if($id == NULL) Event::run('system.52');}
}
if(isset($_POST['submit']))displaydata();// Show data INSIDE form
{
$query = "CREATE TABLE Cars('$columns[$j]')";
$oMysqli = getConnection();
$oMysqli->query($query);
$Insert = "INSERT INTO Cars(Id,column[$j]) VALUES($Id,$column)";
$oMysqli = getConnection();
$oMysqli->query($Insert);
if(isset($_POST['ok']))
{
$plength = count($_POST['column']);
for($j=0;$j<$plength;$j++)
{
$b = $_POST['column'][$j];
$pa = array('column' => $b['column']);
foreach($pa as $l => $m)
{
$pa[$l] = mysql_real_escape_string($m);
}
$columns = $pa['column'];
$columns = $_POST['column'][$j];
for($n=0;$n<$columns;$n++)
{
$x= $_POST['column'][$j];
$ab = array('column' => $c['column']);
foreach($t as $u => $n)
{
$ab[$u] = mysql_real_escape_string($n);
}
$columns = $ab['column'];
$columns = $_POST['column'][$j];
}
}
}
if($result = $mysqli->query($Insert))
{
$k=0;
$column = explode(",",$_POST['columns']);
foreach($column as $c)
{
echo "<td><b>$c</b></td>\r\n";
}
echo "</tr>";
}
}
?>
To answer you question: creating a table is executing a SQL statement against the server.
You should rethink your strategy, creating a table based on user input is bad design.
Use the 'CREATE TABLE' syntax in your query.
All info about it: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Correct php syntax

// query
$sql = "INSERT INTO tool (title,details) VALUES (:title,:details) ";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
':title'=>$title));
Been having trouble with this all day, I've finally got it down to this. If I use the above code, it will just add a new post to the database. This is supposed to be used for editing a post, so obviously I need to edit existing information:
// query
$post = htmlspecialchars($_GET['story']);
$sql = "UPDATE tool SET (title,details) VALUES (:title,:details) WHERE id = $post";
$q = $conn->prepare($sql);
$q->execute(array(':details'=>$details,
':title'=>$title));
'id' is a column in the database. I need it to update the title, and details, for that specific post. I'm just not sure what syntax I'm supposed to be using here.
Thanks for any answers!
===== Second question:
Now I'm back to my old error. Whenever I edit a post, it will lose the title and details, only once. The first time I edit the post, I lose all information, but the rest of the times it will work just fine. Any idea why? Heres the code:
Form from the edit page(may or may not be important, I don't know):
$name = $_SESSION['Username'];
if (in_array($name, $allowedposters)) {
$results = mysql_query("SELECT * FROM tool WHERE id = $post");
while($row = mysql_fetch_array($results)){
$title= $row['title'];
$details= $row['details'];
$date= $row['date'];
$author= $row['author'];
$id= $row['id'];
echo "<a href=story.php?id=";
echo $post;
echo ">Cancel edit</a> <br><br><b>";
echo $title;
echo "</b> <br><br>";
echo '
<form action="edit-new.php?story=';
echo $id;
echo '" method="post" enctype="multipart/form-data">
<textarea rows="1" cols="60" name="title" wrap="physical" maxlength="100">';
echo $title;
echo '</textarea><br>';
?>
<textarea rows="30" cols="60" name="details" wrap="physical" maxlength="10000">
<?php
echo $details;
echo '</textarea><br>';
echo '<label for="file">Upload featured image:</label><br>
<input type="file" name="file" id="file" />';
echo'<br><input type="submit" />';
}
} else {
echo "Not enough permissions.";
}
?>
Here is the SQL, inserting into DB:
<?php
$post = htmlspecialchars($_GET['story']);
$title = mysql_real_escape_string($_POST['title']);
$details = mysql_real_escape_string($_POST['details']);
echo "B<br>";
echo $_POST['title'];
echo '<br>';
echo $_POST['details'];
echo $post;
echo "<br><br>";
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "zzzz";
$dbuser = "zzzzz";
$dbpass = "zzzzzz";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
// query
$sql = "UPDATE tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
':details'=>$details,
':title'=>$title,
':postid' => $post
));
?>
Fix your sql UPDATE syntax
$sql = "UPDATE tool SET title=:title, details=:details WHERE id = :postid";
$q = $conn->prepare($sql);
$q->execute(array(
':details'=>$details,
':title'=>$title,
':postid' => $post
));

Using Multiple Submit Buttons to Delete and Modify

I have an issue where I need to be able to use check boxes in order to delete and modify data in a mysql database.
What is the most efficient way of being able to use multiple submit buttons to either insert data based on what the user types into the text boxes, delete based on the check boxes selected, and modify based on the check boxes selected.
Here is the code I have so far:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
<?php
print "<table width=80% border=1>\n";
$cols = 0;
while ($get_info = mysql_fetch_assoc($result)){
$id = $get_info['Auto'];
if($cols == 0)
{
$cols = 1;
print "<tr>";
print "<th>Select</th>";
foreach($get_info as $col => $value)
{
print "<th>$col</th>";
}
print "<tr>\n";
}
print "<tr>\n";
print "<td><input type='checkbox' name='selected[]' id='checkbox[]' value=$id></td>";
foreach ($get_info as $field)
print "\t<td align='center'><font face=arial size=1/>$field</font></td>\n";
print "</tr>\n";
}
print "</table>\n";
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
mysql_close($conn);
?>
</form>
</BODY>
</HTML>
Insert.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
#header( 'Location: ticket_history.php' );
?>
Delete.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#####################################
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result = mysql_query($sql);
}
header( 'Location: ticket_history.php' );
?>
Any help is appreciated!
Thank you!
Another way to do it is your submit button's have the same name,
So:
<input type="submit" name="submit" value="Delete" />
<input type="submit" name="submit" value="Edit" />
PHP:
switch(strtolower($_POST['submit'])){
case "delete":
// delete logic
break;
case "edit":
// edit logic
break;
}
I would take the insert and delete code and put it on top of the main file instead of having them into files. the simplest way would be to submit the form to itself and based on the submit button clicked run the code block
if($_POST['create']){
// insert code
}
elseif($_POST['delete']){
// delete code
}
continue the logic of if/else/elseif to handle all the cases. This strikes me as the simplest way to get done what you want to do.
Edit:
Not sure but seems like you are handling the $_POST['create'] etc after the HTML code. You should always do that sort of processing BEFORE the html rendering and even before the query to get the records you want to display, this way your get query will always bring up to date results.
When you use multiple submit buttons, you can use PHP to determine which button was pressed. Based on this, you can have your application do different things with the data.
It's not clear what you want to accomplish with multiple buttons. Perhaps you could give more detail.
[Edit]
Looking over your code in detail, it is plain to see that it is quickly becoming a maintenance nightmare. Even if your app is tiny and you don't want to code use MVC pattern, you I still recommend using classes and separating presentation from application logic and from data access. Then it's much easier to maintain the application(fix bugs) and make changes.
If you are building anything more than a trivial script, I recommend using one of the excellent PHP frameworks:
http://framework.zend.com/
http://www.symfony-project.org/
http://codeigniter.com/
http://cakephp.org/
and many more: http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks#PHP
<?php
$host = "localhost";
$user = "root";
$pass = "";
$dbName = "ticket_history";
$table_name = "ticket_history";
################ Connect to the Database and SELECT DATA ####################################
$conn = mysql_connect($host, $user, $pass) or die ("Unable to connect");
mysql_select_db($dbName);
$query = "SELECT Auto,Date,Ticket_Number,Description,Result FROM $table_name";
$result = mysql_query($query);
$count=mysql_num_rows($result);
#############################################################################################
if (isset($_POST['create'])) {
$query_insert = "INSERT INTO ticket_history (Date, Ticket_Number, Description, Result)
VALUES ('$_POST[date]', '$_POST[ticket]', '$_POST[description]', '$_POST[result]')";
$result_insert = mysql_query($query_insert);
if ($result_insert) {
echo "win";
}
else {
echo "fail";
}
}
elseif (isset($_POST['delete'])) {
$ids = array();
foreach($_POST['selected'] as $selected) {
if (ctype_digit($selected)) {
$ids[] = $selected;
}
else {
die('invalid input');
}
$sql_delete = sprintf('DELETE FROM ticket_history WHERE Auto IN (%s)',
implode(',', $ids));
$result_delete = mysql_query($sql_delete);
}
if ($result_delete) {
echo $result_delete;
}
else {
echo "fail";
}
}
elseif (isset($_POST['modify'])) {
header('Location: modify_ticket.php');
}
?>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<table width=50%>
<form method="post">
<table width border='0'>
<tr><td> Date:<input type="text" name="date"/></td>
<td>Ticket #:<input type="text" name="ticket"/></td></tr>
<table>
<tr><td>Description:<TEXTAREA COLS=50 name="description"></TEXTAREA></td></tr>
<tr><td> Result :<TEXTAREA COLS=50 name="result"></TEXTAREA></td></tr>
</table>
<tr><td><input type="submit" name="create" value="Add"/></td></tr>
<tr><td><input type="submit" name="delete" value="Delete"/></td></tr>
<tr><td><input type="submit" name="modify" value="Modify"/></td></tr>
</table>
</table>
I modified the code a little bit and THIS WILL WORK; however, it only works on the SECOND click.
When I select something and click DELETE, it will not delete, but when I do it again it will
Why is this? Thoughts?
Take the code for deletion and insertion above the select, so that the desired deletion of updation is done before you show the data.

Categories