Correct php syntax - php

// 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
));

Related

Updating and deleting from a data table, warning undefined array key

I have been following a lesson on how to make an admin page. I got all the information out of my database to a table on the page. I have an update button and when I change the information and press the button I receive this error: Warning: undefined array key "WebID" in ..\Update.php on line 3
From my search online everyone is trying to change the code so that if array key does not exist: return null. I tried that and the error does not appear no more, but the table does not change.
Any thoughts?
This is the code:
<?php
require_once("DB/DB.php");
$SearchQueryParameter = $_GET["WebID"];
if (isset($_POST["Update"])) {
$Ename = $_POST["Ename"];
$Eid = $_POST["Eid"];
$Erank = $_POST["Erank"];
$Eemail = $_POST["Eemail"];
$Edate = $_POST["Edate"];
$Epassword = $_POST["Epassword"];
$Specialisms = $_POST["Specialisms"];
global $ConnectingDB;
$sql ="UPDATE emp_data SET Ename='$Ename', Eid='$Eid', Erank='$Erank', Eemail='$Eemail', Edate='$Edate', Epassword='$Epassword',
Specialisms='$Specialisms' WHERE WebID='$SearchQueryParameter'";
$Execute = $ConnectingDB->query($sql);
if ($Execute) {
echo '<script>window.open("adminpage.php?WebID=Recored Updated","_self")</script>';
}
}
?>
<?php
<?php
global $ConnectingDB;
$sql = "SELECT * FROM emp_data WHERE WebID='$SearchQueryParameter'";
$stmt = $ConnectingDB->query($sql);
while ($DataRows = $stmt->fetch()) {
$WebID = $DataRows["WebID"];
$Ename = $DataRows["Ename"];
$Eid = $DataRows["Eid"];
$Erank = $DataRows["Erank"];
$Eemail = $DataRows["Eemail"];
$Edate = $DataRows["Edate"];
$Epassword = $DataRows["Epassword"];
$Specialisms = $DataRows["Specialisms"];
}
?>
Html file used to update:
<form id="UpdateForm" method="post" action="Update.php?WebID<?php echo $SearchQueryParameter; ?>">
<div class="form-group">
<button type="submit" name="Update" class="form-control-submit-button">Update</button>
</div>
you have to write the form action like this.. you missed the = sign
action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>"
<form id="UpdateForm" method="post" action="Update.php?WebID=<?php echo $SearchQueryParameter; ?>">
You missed the = sign, in the url

Can't update form data

I am trying to edit form data by displaying the previous saved data on the form and then update it. It shows the data on the form which is saved in database but when i enter the new data it does not get the id of the row. I echo the update query, it shows the changed values but it shows id equals to empty. Here is my code for edit record and update; Edit record is working but update isn't:
<?php
include('connection.php');
$id = '';
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
$udfname = mysql_real_escape_string($_POST["udfname"]);
$udlname = mysql_real_escape_string($_POST["udlname"]);
$udpwd = mysql_real_escape_string($_POST["udpwd"]);
$udeml = mysql_real_escape_string($_POST["udeml"]);
$udnum = mysql_real_escape_string($_POST["udnum"]);
$query="UPDATE form
SET fname = '$udfname', lname = '$udlname', pwd = '$udpwd', eml = '$udeml', num = '$udnum'
WHERE id='$id'";
$res= mysql_query($query);
if($res){
echo "<p> Record Updated<p>";
}else{
echo "Problem updating record. MY SQL Error: " . mysql_error();
}
?>
Form for editing record:
<?php
include('connection.php');
$id = (int)$_GET['id'];
$query = mysql_query("SELECT * FROM form WHERE id = '$id'") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "";
$fname = $row['fname'];
$lname = $row['lname'];
$pwd = $row['pwd'];
$eml = $row['eml'];
$num = $row['num'];
}
?>
<html>
<head>
<title>Edit</title>
<script>
'
'
Jquery code here
'
'
</script>
</head>
<body>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$id;?>">
First Name: <input type="text" name="udfname" value="<?=$fname;?>"><br>
Last Name: <input type="text" name="udlname" value="<?=$lname?>"><br>
Password: <input type="text" name="udpwd" value="<?=$pwd?>"><br>
Email: <input type="text" name="udeml" value="<?=$eml?>"><br>
Contact Number: <input type="text" name="udnum" value="<?=$num?>"><br>
<input type="Submit">
</form>
</body>
</html>
At update time your form is submitted using POST request. So you need to get ID using POST method. So to get ID of hidden field change your code as below:
$id = '';
if( isset( $_POST['ID'])) {
$id = $_POST['ID'];
}
Please try below code
if( isset( $_POST['id']) && $_POST['id']!=null) {
$id = $_POST['id'];
}
Dear i think the problem with your method you are sending the data using post method and its very simple instead of this code
if( isset( $_GET['id'])) {
$id = $_GET['id'];
}
write
if( isset( $_POST['id'])) {
$id = $_POST['id'];
}
and one more thing that is you are using the mysql deprecated function for database kindly use the pdo for this or new mysqli functions.

MySQL Query Issue - PHP variable not passed through includes

So as the title suggests, I am having trouble executing a MySQL query. The query works almost successfully, as all data fields are stored into my database except for one. The query itself is a commenting system for signed in users to comment on any given blog post. The issue I am having is that the variable '$post_id' is not recognized, and therefore '$comment_post_ID' is not stored in my database.
'$post_id' is defined in blogs.php, and after echoing this variable it does exist and is successfully defined. However, this variable is not passed onto commentsubmit.php, which is included in the same file where the variable is defined. Why is this happening?
Here are all the pieces of my code:
blogs.php (shows all posts from all users, or just one post if ?id is set in the url. If ?id is set, users can comment on the single post they are viewing.)
<?php
if (isset($_GET['id'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$post_id = mysqli_real_escape_string($conn, $_GET['id']);
$blog_post = "SELECT * FROM blogs WHERE id = '$post_id'";
$blog_query = mysqli_query($conn, $blog_post);
while ($row = mysqli_fetch_array($blog_query)) {
$title = $row['title'];
$body = $row['body'];
$author = $row['author'];
$author_username = $row['author_username'];
$datetime = time_ago($row['datetime'], $granularity=2);
}
include ("./fullpageblog.php");
if (isset($_SESSION['id'])) {
include ("./blogcomment.php");
include ("./commentsubmit.php");
}
echo "$post_id";
mysqli_close($conn);
}
?>
blogcomment.php (form for users to make a comment)
<div class="row col-sm-12">
<div id="fullPageBlog">
<div id="center-border"></div>
<form action="commentsubmit.php" method="post">
<textarea maxlength="1000" id="blogComment" name="content" placeholder="Write your response..."></textarea>
<input type="submit" name="comment" value="Publish" />
</form>
<script type="text/javascript">$('#blogPost').elastic();</script>
</div>
</div>
commentsubmit.php (comment query itself)
<?php
session_start();
if (isset($_POST['comment'])) {
$conn = mysqli_connect("localhost", "root", "mypassword", "mydbname");
if (mysqli_connect_errno($conn)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit;
}
$comment_post_ID = $post_id;
$comment_author = $_SESSION['full_name'];
$comment_author_email = $_SESSION['email'];
$comment_author_username = $_SESSION['username'];
$comment_date = date("Y-m-d H:i:s");
$comment_content = mysqli_real_escape_string($conn, $_POST['content']);
$user_ID = $_SESSION['id'];
$comment_submit = "INSERT INTO comments (comment_ID, comment_post_ID, comment_author, comment_author_email, comment_author_username, comment_date, comment_content, user_ID) VALUES ('', '$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_username', '$comment_date', '$comment_content', '$user_ID') ";
$comment_query = mysqli_query($conn, $comment_submit);
mysqli_close($conn);
header("Location: blogs.php");
die();
}
?>
You don't include/require the blogs.php script from the commentsubmit.php script, so the code in blogs.php would never be run after a POST that is made directly to commentsubmit.php unless you have some other request processing (i.e. a server-side rewrite or similar) that happens automatically on the server before the request ultimately reaches the portion of code shown in commentsubmit.php above.
<?php
$con = mysql_connect("localhost","root","password");
$con=mysql_select_db("database_name");
error_reporting(0);
session_start();
if(isset($_POST["submit"])){
$comment_author = $_POST['full_name'];
$comment_author_email = $_POST['email'];
$comment_author_username = $_POST['username'];
$sql="select * from table_name where `full_name`='"$comment_author "',`email`='"$comment_author_email "',`username`='"$comment_author_username "'";
$qur=mysql_query($sql);
$row= mysql_fetch_array($qur);
$num= mysql_num_rows($qur);
}
if($num>0){
$_SESSION["full_name"]=$full_name;
$_SESSION["email"]=$comment_author_email;
$_SESSION["username"]=$comment_author_username;
}
else{
echo"Username and Password are wrong";
}
?>

Mysql INSERT statement FAILING when POSTING large array

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

PHP Editing post

I'm having a very annoying problem. Whenever I edit a post, the first time it gets edited, it will lose all of its information. I can't figure it out, I've worked on it for 2 days.
Heres the form code:
<?php
$post = htmlspecialchars($_GET["id"]);
$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 actual php code, inserting information into the database:
.
.
<?php
$post = $_GET['story'];
$title = $_POST['title'];
$details = $_POST['details'];
echo 'Updated.';
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "x";
$dbuser = "xx";
$dbpass = "xxx";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tool SET title=:title, details=:details WHERE id = '$post'";
$q = $conn->prepare($sql);
$q->execute(array(
':details'=>$details,
':title'=>$title,
));
?>
Again, I would like to mention, the only problem is that, the first time I edit the post, it will lose its information. It will never happen to that specific post after that.
The editing works flawlessly, after that.
This doesn't directly answer your question - it would be useful to know what you're actually getting for $_GET['id'], what actual SQL is running on your database and what the generated content of your form looks like.
However:
$post = htmlspecialchars($_GET["id"]);
Is wrong. htmlspecialchars escapes data for output to the client. Encoding special characters for SQL is not going to protect you from SQL injection attacks.
Since $post is expected to be an integer (presumably), this is sufficient:
$post = (int)$_GET['id'];
But be sure to check that a valid integer is returned, and throw an appropriate error if not.
Don't forget to do this again in edit-new.php - even better, use a parametized value like you have done for title and details.
Finally, you should use htmlspecialchars to escape $details and $title in the form. Otherwise content like </textarea> will not be displayed correctly and you are vulnerable to XSS flaws (e.g. followed by <script>alert("I'm going to do bad things now");</script>

Categories