Using a variable with a changing value in MySQL query? - php

I'm building a tagging system for a site I'm working on. I have a variable for the url of the image that changes as the user selects different pictures. I'm using a MySQL command to display 3 tags for the selected picture, but it isn't working if I give it that changing variable. However, if I manually insert a url of an image, the captions show. However, these will show no matter what picture you're on so that doesn't really help. If I store a url under a variable, that works too, but not with the one that changes all the time.
Here's the site.
I know this isn't very easy to understand, so please let me know if you want me to try re-explaining something or if you want me to include some of the code. Thanks!
EDIT: Ok, I'll retry here. First, here's the code:
<?php
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//Do the query
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT 5");
// Generate an array of all images.
$images = array();
while($image = mysql_fetch_array($query)) {
// Adds each image to the images array.
$images[] = $image;
}
$image['filename'] = $current_image;
$query_captions = mysql_query("SELECT * from captions WHERE image = '$current_image' ORDER BY idnum DESC LIMIT 3");
$captions = array();
while($caption = mysql_fetch_array($query_captions)) {
$captions[] = $caption;
}
?>
<?php
// Beginning attempt at a caption script.
?>
<html>
<head>
<title>Home - Site in Development</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script type="text/javascript">
// Switches the url to view large image.
function switchImageUrl(url, width, height) {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
x.style.display = 'none';
y.style.display = 'none';
z.value = '';
document.getElementById('center_frame').style.backgroundImage = 'url' + '(' + url + ')';
document.getElementById('center_frame').style.width = width;
document.getElementById('center_frame').style.height = height;
}
</script>
<!--Toggles view of caption selection tools and resets after.-->
<script type="text/javascript">
function selectionToggle() {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
if(x.style.display == 'block')
x.style.display = 'none';
else
x.style.display = 'block';
x.style.width = '75px';
x.style.height = '75px';
x.style.top = '0px';
x.style.left = '0px';
if(y.style.display == 'block')
y.style.display = 'none';
else
y.style.display = 'block';
z.value = '';
}
</script>
<script type="text/javascript">
function collectAttributes() {
var cap = document.getElementById('caption_selection');
var cw = document.getElementById('cap_width');
var ch = document.getElementById('cap_height');
var cl = document.getElementById('cap_left');
var ct = document.getElementById('cap_top');
cw.value = cap.style.width;
ch.value = cap.style.height;
cl.value = cap.style.left;
ct.value = cap.style.top;
}
</script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#caption_selection").draggable({
containment : "#center_frame"
});
$("#caption_selection").resizable({
containment : "#center_frame"
});
});
</script>
</head>
<body onLoad="CalculateAllImageWidthes()">
<div id='account_links'>
<?php
if ($_SESSION['username']) {
echo "Welcome $username!";
} else { ?>
<a href='login.php'>Login</a> | <a href='register.php'>Register</a>
<?php } ?>
</div>
<h1>Picture Captions</h1>
<br/>
<br/>
<div id="left_bar">
Submit a picture here.
<hr/>
<h2>Top Images</h2>
<br/>
<div id="front_pg_images">
<?php foreach($images as $image) { ?>
<a onClick="switchImageUrl('<?php echo $image['filename']; ?>', '<?php echo $image['width']; ?>', '<?php echo $image['height']; ?>')"><img src="<?php echo $image['filename'];?>" width="72px" height="58px" id="front_pg_thumbnail"/></a>
<?php echo $image['name']." - by ".$image['submitter']; ?> <br/>
<br/>
<?php } ?>
</div>
</div>
<div id="center_frame" style="width: <?php echo $image['width']; echo "px" ?>; height: <?php echo $image['height']; echo "px" ?>; background-image: url('<?php echo $image['filename'];?>')" >
<?php foreach($captions as $caption) { ?>
<div id="set_caption" style="width:<?php echo $caption['width'].'px';?>;height:<?php echo $caption['height'].'px';?>; left:<?php echo $caption['posleft'].'px';?>; top:<?php echo $caption['postop'].'px';?>"><?php echo $caption['text'];?></div>
<?php } ?>
<div id="caption_selection" style="display:none">
</div>
</div>
<div id="toggle_select_container">
<input type="button" id="toggle_select" onClick="selectionToggle()" value="Caption"/>
<div id="caption_input" style="display:none">
<form action="postcaption.php" method="post" onSubmit="collectAttributes()">
<br/>
<textarea name="caption_text" cols="27" rows="4" id="input_value"></textarea><br/>
<input type="hidden" name="filename" value="<?php echo $image['filename'];?>"/>
<input type="hidden" name="width" value="" id="cap_width"/>
<input type="hidden" name="height" value="" id="cap_height"/>
<input type="hidden" name="left" value="" id="cap_left"/>
<input type="hidden" name="top" value="" id="cap_top"/>
<input type="submit" value="Post Caption"/>
</form>
</div>
</div>
</body>
</html>
It uses a JavaScript function to change the image when the user clicks on the thumbnail. Take note of the foreach. For everywhere else on the page, the $image['filename'] has worked perfectly for similar uses, but it just isn't working when I try to use it with this.

Related

sql and php variable

i want to create form to upload file into img dir(i know how to do that),and insert an html code and php variable to database(that works fine), the problem is when i fetch the html code from database it shows <img src=img/$rand>, i what it to show the the result of varible not the name, sorry for my bad english
here is my full code:
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$rand = substr(md5(microtime()),rand(0,26),5);
?>
<!DOCTYPE html>
<html>
<head>
<title>Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<?php
if(isset($_POST['insert'])){
$fu = $_FILES['image'];
$image_tmp_name= $_FILES['image']['tmp_name'];
$image_name = $_FILES['image']['name'];
move_uploaded_file($image_tmp_name,"img/$image_name");
rename("img/$image_name", "img/$rand");
//echo "<img class='iwalls' data-toggle='modal' data-target='' src='img/$image_name' alt='Loading...'>";
}
?>
<?php
if(isset($_POST["insert"]))
{
$file = '<img src=img/$rand>';
$sql = "INSERT INTO tbl_images(name) VALUES ('$file')";
if(mysqli_query($connect, $sql))
{
echo '<script>alert("Image Inserted into Database")</script>';
} else{
echo '<script>alert("Failed")</script>';
}
}
?>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
<?php
$query = "SELECT * FROM tbl_images ORDER BY id DESC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div>";
echo $row ['name'];
echo "</div>";
}
?>
</tr>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
When using single quotes, the string will be as is it is.
$rand = "hello.png";
$file = '<img src=img/$rand>';
// $file is <img src=img/$rand>
You need double quotes for string interpolation
$file = "<img src=img/$rand>";
// $file is <img src=img/hello.png>;

Is There Any Way I Can Do This Without Refreshing The Page?

I am trying to create and edit button, like Reddit has, for my forum. I have got it to work but I was wondering if I'd be able to do it without having to refresh the page.
For example, when I click the edit button, it reloads the page and displays the form for editing, then when I click save it will reload yet again to display the new edited post.
Code (EDITED from IncredibleHat's answer):
<?php
session_start();
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
// get value of id that sent from address bar
$id = $_GET['id'];
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_array($result);
/*Check if topic is locked or not */
$locked = $rows['locked'];
if ($_SESSION['username'] == $rows['username']) {
$editPost = true;
}
?>
<head>
<!-- ****** faviconit.com favicons ****** -->
<link rel="shortcut icon" href="../images/favicon.ico">
<!-- ****** faviconit.com favicons ****** -->
<link id ="pageStyle" rel="stylesheet" href='../css/defaultStyle.css' type='text/css'> <!-- Loads Default Stylesheet -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto' type='text/css'>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<div id="mainContent">
<div id="question">
<p id="date"><?php echo $rows['datetime']; ?></p>
<h2><?php echo $rows['topic']; ?></h2>
<b><p><?php echo $rows['username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['detail']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a><br>', '<p id="post">'.$text.'</p>');
} else {
?>
<p id="post"><?php echo htmlspecialchars($rows['detail']); ?></p>
<?php
}
if ($editPost == true) {
$_SESSION['detail'] = $rows['detail'];
$_SESSION['id'] = $rows['id'];
?>
<style>
#editPostButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
#editPostButton.dark {
color: white;
background-color: #1C1C1C;
}
</style>
<input type="submit" value="Edit" name="editPostButton" id="editPostButton" data-postId="<?php echo $rows['id']; ?>">
<div id="editFormBlock"></div>
<script>
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e) {
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn) {
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e) {
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn) {
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
<?php
}
?>
</div>
<?php
$tbl_name2="fanswer"; // Switch to table "forum_answer"
$sql2 = "SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2 = mysqli_query($conn, $sql2);
$row_cnt = mysqli_num_rows($result2);
if ($row_cnt > 0) {
?>
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
} else {
?>
<p><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
?>
</div>
<?php
}
} else {
?>
<div id="answers">
<p style="color: red;">There doesn't seem to be anything here</p>
<?php
}
$sql3 = "SELECT view FROM $tbl_name WHERE id='$id'";
$result3 = mysqli_query($conn, $sql3);
$rows = mysqli_fetch_array($result3);
$view = $rows['view'];
// if have no counter value set counter = 1
if(empty($view)) {
$view = 1;
$sql4 = "INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
}
// count more value
$addview = $view+1;
$sql5 = "update $tbl_name set view='$addview' WHERE id='$id'";
$result5 = mysqli_query($conn, $sql5);
mysqli_close($conn);
?>
</div>
<h3>Post A Reply:</h3>
<form name="form1" method="post" action="add-answer" autocomplete="off">
<label>Reply: </label>
<?php
if ($locked == 1) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>🔒 This topic is locked! 🔒</textarea><br>';
} else if ($_SESSION['logged_in'] != true) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>â›” You must login to reply! â›”</textarea><br>';
} else {
echo '<textarea name="a_answer" id="a_answer" maxlength="300" required style="width: 800px;"></textarea><br>
<div class="g-recaptcha" data-sitekey="6LdrxD4UAAAAACAaVAR6U9BjOEDC9-j4QaOzBsFh"></div>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Reset">';
}
?>
<input name="id" type="hidden" value="<?php echo $id; ?>">
</form>
</div>
</body>
ajaxhandler.php:
<?php
session_start();
$detail = $_SESSION['detail'];
$id = $_SESSION['id'];
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
?>
<style>
#post, #editPostButton {
display: none;
}
#saveButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
</style>
<form id="editForm">
<textarea name="detail"><?php echo $detail; ?></textarea><br>
<input type="button" id="saveButton" value="Save">
</form>
<?php
}
if ($_POST['action'] == 'saveform') {
// do save process to db
// echo out a new static post html block
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$sql = "UPDATE $tbl_name SET detail = '$detail' WHERE id=$id";
$result = mysqli_query($conn, $sql);
}
}
?>
Two ways you could do the toggling of an edit form.
Load in more html (sub parts, not whole html documents) with ajax calls, and replace existing elements with the new html chunks based on actions. Click the edit button, it calls ajax to 'get the form block', and then it replaces some slot on the page with it. Submitting the form, tosses that form, and replaces it with the new static text block. This is generally a cleaner way to handle it.
Have all the relevant bits in the html DOM on first load of the php script. Have many parts hidden. Then clicking certain buttons, or doing actions shows/hides elements based on those actions. This is easier, but not as clean, as all your form submit elements and actions, as well as the original static parts, are all in the HTML on every general page load.
An example of loading in a edit form on edit-button click, and swapping content blocks:
Basic static HTML framework (from first load of main.php):
<p id="post">[the original post html here]</p>
<?php if ($editPost == true) { /* dont bother if they have no edit rights */?>
<input type="button" id="editPostButton" value="Edit" data-postId="<?php echo $postId;?>">
<div id="editFormBlock"></div>
<?php }?>
Script area (jquery required):
<script language="Javascript" type="text/javascript">
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e){
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn){
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e){
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn){
$("#post").html( htmlReturn ); // replace static post content
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
The ajaxhandler.php:
// Have blocks that pertain to the $_POST['action']
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
// do a database select on using the postId
// grab the data you wish to use in the edit form
// build a form and echo it out for the ajax return
echo '
<form id="editForm">
<input type="hidden" name="postId" value="'. $row['id'] .'">
<textarea name="detail">'. $row['detail'] .'</textarea>
<input type="button" id="saveButton" value="Save">
</form>
';
}
if ($_POST['action'] == 'saveform') {
// put your "save to database" code here
// that uses $_POST['postId'], $_POST['detail'] etc
// after saving, grab a fresh copy of the post
// and then echo out a new static html #post content
echo htmlspecialchars($row['detail']);
}
}
I hope this was clear enough to understand to get a foothold on what you wish to do. There is a lot more you can do, with an extra errorBlock to show errors, and handling of results. You can even push in some animations too. Endless possibilities.
NOTE: I should warn you though, that this is all based off your example, where you are showing just one post, and one edit form. This uses "ID"s, which must be unique on the page. If you are planning on pouring many posts on ONE page, you will need to adjust everything to use classes and enumerated ID's to keep the unique.

When submit form, page won't refresh with new data from sql server until refresh?

Problem
index.php is a page that displays albums from a server hosted by MAMP using SQL. In grid.php I query the server and displays the albums in a grid. index.php also has a form in addalbum.php that allows the user to add an album to the database.
However, when the user submits the form in addalbum.php although the database gets updated, the page doesn't show the new data even though I do:
<form action="../p3/index.php" method="post">
I have to either refresh the page or click on it again to see the updated data. I'm confused as to why this is happening since I set the form action to index.php so it should refresh the page.
If anyone has some advice on that it would be greatly appreciated!
Code
index.php
<?php
$name = "Albums";
require_once('config.php');
require_once("nav.php");
require_once("php/header.php");
require_once("php/grid.php");
require_once("php/footer.php");
// require_once("../P3_M2/php/header.php");
// require_once("../P3_M2/php/grid.php");
// require_once("../P3_M2/php/footer.php");
require_once('php/login.php');
require_once('php/addalbum.php');
$error_log = addAlbumToDatabase();
foreach($error_log as $error){ //debuggin
echo "<h1>$error</h1>";
}
?>
config.php
<?php
define( 'DB_HOST', 'blahblahblah');
define('DB_NAME', 'blahblahblah');
define('DB_USER', 'blahblahblah');
define('DB_PASS','blahblahblah');
//Set up sqli
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASS, DB_NAME );
if ($mysqli->errno) { //Was there an error connecting to the database?
//The page isn't worth much without a db connection so display the error and quit
print($mysqli->error);
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>
<?php echo "$name" ?>
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Styling-->
<link type="text/css" rel="stylesheet" href="css/main.css" />
<link type="text/css" rel="stylesheet" href="css/grid.css" />
<link type="text/css" rel="stylesheet" href="css/form.css" />
<?php
$nameLowercased = strtolower($name);
echo "<link type='text/css' rel='stylesheet' href='css/$nameLowercased.css'/>";
?>
<!--Custom icon-->
<link href="https://file.myfontastic.com/fNQ9F99nd88vQm96ESUaLW/icons.css" rel="stylesheet" />
<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Javascript-->
<script type="text/javascript" src="js/main.js"></script>
</head>
grid.php
<?php
/*DATA*/
//Query for each page
$queryFor = array(
'Albums' => 'SELECT * FROM Album;',
'Photos' => 'SELECT * FROM Image;',
'Album' => "SELECT * FROM Image WHERE id IN
(SELECT image_id FROM AIDict WHERE album_id = $album_id);"
);
//Loop through the $result rows fetching each one as an associative array
$printGridFor = array(
'Albums'=> function($row){
$albumId = $row['id'];
$albumTitle = $row['title'];
$albumDate = $row['date_created'];
$dateFormatted = date("F d, Y", strtotime($albumDate));
$creator = $row['creator'];
print("<div class='grid-square'>
<a href='album.php?id=$albumId'class='grid-info'>
<h1>$albumTitle</h1>
<h2>$dateFormatted</h2>
<h2>$creator</h2>
</a>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit''><span class='icon-pencil'></span></button>
</div>");
},
'Photos' => function($row){
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
},
'Album' => function($row){ //Same as 'Photos'
$imgTitle = $row['title'];
$filename = $row['file_name'];
$filepath = $row['file_path'].$filename;
print("<div class='grid-square'>
<img src='$filepath' alt='$imgTitle ''>
<button class='delete'><span class='icon-trash-can'></span></button>
<button class='edit'><span class='icon-pencil'></span></button>
</div>");
}
);
/*SQL*/
//Get the data
$query = $queryFor[$name];
$result = $mysqli->query($query);
if (!$result) { //If no result, print the error
print($mysqli->error);
exit();
}
?>
<div class="grid">
<?php
while ($row = $result->fetch_assoc()) {
$printGridFor[$name]($row);
}
?>
</div>
<button class="add"><span class="icon-plus"></span></button>
addalbum.php
<?php
function addAlbumToDatabase(){
$errors = array();
if(isset($_POST['submit'])){
global $mysqli;
$maxIdQuery = "SELECT MAX(id) FROM Album";
$maxIdResult = $mysqli->query($maxIdQuery);
if (!$maxIdResult) { print($mysqli->error); exit();} //If no result, print the error
if($row = $maxIdResult->fetch_row()){
$maxId = $row[0]; //Get max id
//Insert album into database
$stmt = $mysqli->prepare("INSERT INTO Album (id, title, date_created, date_modified, location, creator)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $album_id, $title, $date_created, $date_modified, $location, $creator);
$album_id = $maxId + 1;
$title = (isset($_POST['album-title'])) ? $_POST['album-title'] : "Untitled";
date_default_timezone_set('America/New_York');
$todays_date = date('Y-m-d');
$date_created = (!empty($_POST['date-created'])) ? $_POST['date-created'] : $todays_date;
$date_modified = (!empty($_POST['date-modified'])) ? $_POST['date-modified'] : $date_created;
$location = (isset($_POST['location'])) ? $_POST['location'] : NULL;
$creator = (isset($_POST['creator'])) ? $_POST['creator'] : NULL;
$executed = $stmt->execute(); //execute statement
$stmt->close(); //close statement
if(!$executed){ //Add to error log
$errors[] = "Unsucceful when inserting $title into database";
$errors[] = $mysqli->error;
}
return $errors;
}
$errors[] = "$title not inserted into database";
return $errors;
}
$errors[] = "Nothing added b/c submit button not pressed";
return $errors;
}
?>
<div class="form-screen">
<button class="close close-form"><span class="icon-x"></span></button>
<form action="../p3/index.php" method="post">
<div class="form-wrapper">
<h1>Add Album</h1>
<input type="text" name="album-title" placeholder="Album Title*" required>
<input type="text" name="date-created" class="date" placeholder="Date Created">
<input type="text" name="date-modified" class="date" placeholder="Date Modified">
<input type="text" name="location" placeholder="Location">
<input type="text" name="creator" placeholder="Author*" required="">
<button type="submit" class="field submit" name="submit" value="submit">Create Album</button>
</div>
</form>
</div>
main.js
$(document).ready(function () {
//Show/Hide edit & delete buttons
$(".grid").on("mouseenter", ".grid-square", function () {
$(this).find(".delete").fadeIn(100);
$(this).find(".edit").fadeIn(100);
});
$(".grid").on("mouseleave", ".grid-square", function () {
$(this).find(".delete").fadeOut(100);
$(this).find(".edit").fadeOut(100);
});
//Show/Hide nav bar
$(".closeNavBtn").on("click", function () {
$(".sidenav").css("width", "0px");
});
$(".menu").on("click", function () {
$(".sidenav").css("width", "250px");
});
$(window).scroll(function (event) {
if ($(".sidenav").width() === 250) {
$(".sidenav").css("width", "0vw");
}
});
//Show/Hide login screen
$(".login").on("click", function () {
$(".login-screen").fadeIn(300);
});
$(".close-login").on("click", function () {
$(".login-screen").fadeOut(300);
});
//Show/Hide form screen
$(".add").on("click", function(){
$(".form-screen").fadeIn(300);
});
$(".close-form").on("click", function(){
$(".form-screen").fadeOut(300);
});
//Customize input label based on file
var input = document.querySelector('.inputfile');
if(input != null){customizeInputLabel(input);}
//Datepicker
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(".date").datepicker({
inline: true,
showOtherMonths: true, dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
});
});
//customizeInputLabel changes label when select file
function customizeInputLabel(input) {
var label = input.nextElementSibling
, labelVal = label.innerHTML;
input.addEventListener('change', function (e) {
var fileName = '';
if (this.files && this.files.length > 1) fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
else fileName = e.target.value.split('\\').pop();
if (fileName) label.querySelector('span').innerHTML = fileName;
else label.innerHTML = labelVal;
})
}
File directory structure

print_r($_REQUEST) not showing all datas after showing few datas

print_r($_REQUEST) is not showing all the datas after redirecting from a page from which form is being submitted. In the redirected page it is showing some datas but not all.In the localhost all the requested datas are showing fine,but in the server the problem is occurring.
I have created a php.ini & put max_execution_time = 160; post_max_size = 250M; into the file & uploaded it in the server. But still couldn't get any solution.
Here is code. Actually some page are included after checking condition and then the form is being submitted after filling fields.
include("configuration.php");
if(isset($_REQUEST["save_update"]) && $_REQUEST["save_update"]!="")
{
include("quotation_save.php");
header("location:http://mpsinfoservices.com/projects/topline/quotation.php?enquiry_id=".$_REQUEST["enquiry_id"]."&displaying_id=".$_REQUEST["displaying_id"]);
}
$enqid = $_REQUEST["enquiry_id"];
$displaying_id = $_REQUEST["displaying_id"];
$len_of_disp = strlen($displaying_id);
/*if(preg_match('/E/',$displaying_id))
{
echo substr($displaying_id,0,6);
echo "<br/>".substr($displaying_id,strlen(substr($displaying_id,0,6)));
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
$ch_from_find_str = 'F';
$find_str = substr($displaying_id,0,7);
$ch_from_find_str = substr($find_str,6,1);
}
if(preg_match('/PKG/',$displaying_id))
{
$find_str = substr($displaying_id,0,9);
echo $find_str;
}
*/
$sql_enquiry = mysql_query("SELECT * FROM `enquiry_master` WHERE `id`='".$enqid."' AND `displaying_id`='".$displaying_id."'");
$row_enquiry = mysql_fetch_assoc($sql_enquiry);
$sql_client_info = mysql_query("SELECT * FROM `client_info` WHERE `client_id`='".$row_enquiry['customer_id']."'");
$row_client_info = mysql_fetch_assoc($sql_client_info);
?>
<link type="text/css" href="css/cupertino/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
<link type="text/css" href="css/jquery.dataTables_themeroller.css" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/function.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<link type="text/css" href="css/style.css" rel="stylesheet">
<style>
.client_name
{
border:none;
}
.client_name_mouseover
{
border:1px solid #000;
}
</style>
</head>
<body>
<?php include("includes/header.php"); ?>
<div id="page-container">
<?php
include("includes/left_menu.php");
?>
<div id="page_content" style="float:left;">
<div style="margin-top:25px;">
<div style="padding-top:10px;">
<div style="color:#000;font-weight:bold;font-size:12px;font-family:verdana;">Client Details</div>
<div>Name:- <input type="text" name="client_name" id="client_name" class="client_name" value="<?php echo $row_client_info["client_firstname"].$row_client_info["client_middlename"].$row_client_info["client_lastname"];?>" readonly="readonly"/></div>
<div>Email:- <?php echo $row_client_info["client_email_id"]; ?>
</div>
<div>
<?php
$sql_quotation_insert_status = mysql_query("SELECT `status` FROM `quotation_insert_status` WHERE `enquiry_id`='".$enqid."'");
if( mysql_num_rows($sql_quotation_insert_status)>0)
{
$res_quotation_insert_status = "insert";
}
else
{
$res_quotation_insert_status = "";
}
?>
<form name="quotation" class="quotationfrm" method="post" enctype="multipart/form-data" action="quotation.php">
<input type="hidden" name="displaying_id" value="<?php echo $displaying_id; ?>"/>
<input type="hidden" name="enquiry_id" value="<?php echo $enqid; ?>"/>
<input type="hidden" name="save_update" <?php if($res_quotation_insert_status=="insert"){?>value="update" <?php } if($res_quotation_insert_status==""){?> value="save_quotation" <?php } ?>/>
<?php
if(preg_match('/E/',$displaying_id))
{
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/flight_quotation.php");
}
if(preg_match('/T/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/train_quotation.php");
}
if(preg_match('/H/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/hotel_quotation2.php");
}
if(preg_match('/CC/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/carrental_quotation.php");
}
if(preg_match('/I/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/insurance_quotation.php");
}
if(preg_match('/V/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/visa_quotation.php");
}
if(preg_match('/CR/',substr($displaying_id,strlen(substr($displaying_id,0,6)))))
{
include("quotation/cruise_quotation.php");
}
}
if(preg_match('/PKG/',$displaying_id))
{
if(preg_match('/H/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/hotel_quotation2.php");
}
include("quotation/package_quotation.php");
if(preg_match('/F/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/flight_quotation.php");
}
if(preg_match('/V/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/visa_quotation.php");
}
if(preg_match('/T/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/train_quotation.php");
}
if(preg_match('/CC/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/carrental_quotation.php");
}
if(preg_match('/I/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/insurance_quotation.php");
}
if(preg_match('/CR/',substr($displaying_id,strlen(substr($displaying_id,0,7)))))
{
include("quotation/cruise_quotation.php");
}
}
?>
<input type="button" class="save_quotation" <?php if($res_quotation_insert_status=="insert"){?> value="Update" <?php } if($res_quotation_insert_status==""){ ?> value="Save The Quotation" <?php } ?> style="margin-top:20px;" <?php if($res_quotation_insert_status=="insert"){ ?> name="save" <?php } if($res_quotation_insert_status==""){ ?> name="update" <?php } ?>/>
<?php if($res_quotation_insert_status=="insert"){?>
<input type="button" class="sendQuotation" value="Send Quotation"/>
<?php
}
?>
</form>
</div>
</div>
<script>
$(function(){
var no=0;
$("form").each(function(){
no++;
});
var suc = 0;
$("#client_name").live("mouseover",function(){
$(this).removeClass("client_name");
$(this).addClass("client_name_mouseover");
});
$("#client_name").live("mouseout",function(){
$(this).removeClass("client_name_mouseover");
$(this).addClass("client_name");
});
$(".mail_to_client").live("click",function(){
$.post("flight_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".flight_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});
$.post("train_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".train_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});
/*$.post("hotel_quotation_mail.php?enquiry_id=<?php echo $enqid; ?>",$(".hotel_quotation_frm").serialize(),function(data){
if(data=="success")
{
suc++;
}
if(no==suc)
{
$.post("mail_to_client.php?enquiry_id=<?php echo $enqid; ?>");
}
});*/
});
$(".save_quotation").live("click",function(){
$(".quotationfrm").submit();
});
$(".sendQuotation").live("click",function(){
for(var instanceName in CKEDITOR.instances)
CKEDITOR.instances[instanceName].updateElement();
var formData = $(".quotationfrm").serialize();
$.post("quotation_pdf.php",function(){
window.open("quotation_pdf.php?"+formData);
});
});
});
</script>
In some cases due to html elements in the data it will render only few, try checking View Source of that page.
The content and order of $_REQUEST is affected by variables_order directive in php.ini (see Description of core php.ini directives)
So, it is possible, that on your production environment value of variables-order directive differs from that in your development environment (localhost).
For example, set variables_order = "GPCS" in order to have G-$_GET, P-$_POST, C-$_COOKIE, S-$_SERVER arrays and all values from that arrays in $_REQUEST.

How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. I'm working on the comment system. I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken.
Here's the page that contains the form. (fullpost.php)
<!DOCTYPE html>
<html>
<?php
include ('functions.php');
connectDB();
$id = $_GET['id'];
$result = queryDB('SELECT * FROM posts WHERE id='.$id);
$post = mysql_fetch_array($result);
?>
<head>
<title><?php echo $post['title']; ?> - SimpleBlog</title>
<link rel="stylesheet" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".commentform").validate();
});
</script>
</head>
<body>
<div id="header">
SimpleBlog
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
echo '<div class="post">';
echo '<div class="postheader">';
echo '<h1>'.$post['title'].'</h1>';
echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
echo '</div>';
echo '<p>'.$post['fullpost'].'</p>';
echo '</div>';
//display comments form
?>
<div id="commentform">
<form action="commentsubmit.php" method="POST" class="commentform"/>
<?php
//if not logged in, display a name field
if (!loggedIn()) {
echo '<label for="author">Name: </label><br />';
echo '<input type="text" name="author" class="required"/><br />';
}
?>
<label for="comment">Comment: </label><br />
<textarea type="text" name="comment" class="required"></textarea><br />
<input type="hidden" value="<?php echo $id; ?>" name="postid"/>
<input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
</form>
</div>
<?php
}
else {
//no posts found
echo "That post doesn't exist!";
}
$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);
//comments found, display them
if (mysql_num_rows($result) >0) {
if (mysql_num_rows($result) == 1) {
echo '<h5>'.$numcomments.' Comment:</h5>';
}
if (mysql_num_rows($result) > 1) {
echo '<h5>'.$numcomments.' Comments:</h5>';
}
while($comment = mysql_fetch_array($result)) {
echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
echo '<p>'.$comment['text'].'</p>';
}
}
else {
//no comments found
echo '<h4>No comments</h4>';
}
?>
</div>
</body>
</html>
Here's the page it submits to. (commentnew.php)
<?php
//creates a new comment
include('functions.php');
//form submitted
if (isset($_POST['submit'])) {
//set $author if not logged in
if(!loggedIn()) {
//check if username is taken
connectDB();
$result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
if (mysql_num_rows($result) > 0) {
die('That name is taken!');
}
else {
//username is not taken
$author = mysql_real_escape_string($_POST['author']);
}
}
else {
//user is logged in, set author to their username
$author = $_SESSION['username'];
}
//$author is set, submit
if (!empty($author)) {
$postid = mysql_real_escape_string($_POST['postid']);
$comment = mysql_real_escape_string($_POST['comment']);
$date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));
queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
echo 'Comment Sent!';
}
}
?>
I tried using $.ajax in the script tags, but it seems to do nothing. Can I get an example of how to properly use it? How do I get it to pull the message from commentnew.php? Am I going about checking for the username the wrong way? Should I be using jQuery's validation plugin somehow?
in general:
var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
alert("Response: " + data);
});
Try this
$("form.commentform").submit(function(e){
e.preventDefault();
$.post({
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(reponse){
//here response will contain whatever you send from the server side page
}
});
}):
Look into jquery ajax function. That's what I use. http://api.jquery.com/jQuery.ajax/

Categories