MySQL Result in $row will not echo in if conditional - mysql

I am trying to get the row queried in preceding code to echo inside of this if conditional if the user clicks the modify video link. However, when I echo the $video variable directly above the if ($videoEdit) { conditional, it displays on page, but if I try to echo it inside the if ($videoEdit) { conditional, it will not output for some reason. I'm confused. Here is my code (query not included, but echo $video does output proper results before conditional)
Addition:::
require ('../mysql_connect.php'); // Connect to DB
// Handle Video Edit
if ($_GET['video'] == "EDIT") {
$videoEdit = TRUE;
}
$query = "SELECT inventory.inv_key, inventory.mdl_key, inventory.serial, inventory.date_aquired, inventory.location, inventory.price, model.mdl_key, model.man_key, model.cls_key, model.sub_cls_key, model.model, model.video, model.picture, model.pdf, subclass.sub_cls_key, subclass.subclass, class.cls_key, class.class, manufacturer.man_key, manufacturer.manufacturer FROM inventory, manufacturer, model, class, subclass WHERE inventory.mdl_key='$_GET[mdl_key]' AND model.mdl_key='$_GET[mdl_key]' AND class.cls_key='$_GET[cls_key]' AND subclass.sub_cls_key='$_GET[sub_cls_key]' AND manufacturer.man_key='$_GET[man_key]' AND manufacturer=manufacturer.manufacturer AND class=class.class AND subclass=subclass.subclass";
$result = #mysql_query ($query); // Run the query
while ($row = mysql_fetch_array
($result, MYSQL_ASSOC)) {
$model = $row['model'];
$mdl_key = $row['mdl_key'];
$video = $row['video'];
$picture = $row['picture'];
$pdf = $row['pdf'];
$description = $row['description'];
$manufacturer = $row['manufacturer'];
$man_key = $row['man_key'];
}
Addition Above::::
if ($_GET['video'] == 'EDIT') {
$videoEdit = TRUE;
}
while ($row = mysql_fetch_array($result)) {
$video = $row['video'];
}
if ($videoEdit) { // <-- boolean comparison
echo '<form action="edit_media.php" method="post">
<p>Video Link: <input type="text" name="serial" size="25" maxlength="100" value=';
if (isset($video))
echo $video;
}
echo ' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />
</form>';
}
Addition:: this is, in my code, directly below the above code
if ($video != "") {
echo '<iframe width="420" height="315" src=' . $video . ' frameborder="0" allowfullscreen></iframe> | <a href=edit_media.php?video=EDIT&mdl_key=' . $mdl_key . '&man_key=' . $man_key . '>Modify Video Link</a>';
} else {
echo "Video Not Present | <a href=edit_media.php?video=EDIT>Add a Video</a>";
}

You are missing an echo before the remainder of your html string ' />< /p>...'
if (isset($video))
echo $video;
echo ' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" /></form>';

Most likely, $video is not set.
You should try to echo $video; after the while loop. Also, you should not be using a loop unless if you're only fetching a single result.
$row = mysql_fetch_array($result);
$video = $row['video'];
echo $video;
Update
Here's how I would approach your problem (obviously replacing mysql_ functions):
if ($_GET['video'] == 'EDIT') {
$result = mysql_query("SELECT ... ");
$row = mysql_fetch_array($result);
$video = $row['video'];
echo '<form action="edit_media.php" method="post">
<p>Video Link: <input type="text" name="serial" size="25" maxlength="100" value='";
if (isset($video)) {
echo $video;
}
echo '" /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />
</form>';
}
}
Also noticed that you were missing the open curly bracket ({), and double quotes around the value of $video in the HTML.

Not sure if this is the answer, but looks like you need another "echo" before continuing the loop, after trying to echo out the $video content. Before this:
' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />

Related

HTML/PHP inline update and delete for each row of a table

Having a bit of a problem with an inline 'update' button, where I am pulling data from a mysql table (done), presenting that data to the screen using 'foreach' (done) and have a update and delete button on each line that POSTs the correct button 'name' and ID of the user (done).
However what the $_POST array isnt parsing is the correct data with the row information.... It does parse Changes to the bottom row, but if you change another row, it just parses the last row again....
<input type="hidden" name="action" value="submit" />
<pre></pre>
<?php print_r($_POST);?>
<?php
echo '<table class="table table-condensed">';
echo '<thead><tr><th style="width: 15%">Name</th><th style="width: 25%">Login</th><th style="width: 25%">Email</th><th style="width: 7%">Role</th><th style="width: 7%">Group</th><th style="width: 15%">LoftID</th><th>Edit</th><th>Delete</th></tr></thead><tbody>';
foreach($users as $person){
echo '<tr>';
echo '<td><input type="text" class="form-control" name="name" id="'.$person['id'].'" placeholder="Name" value="'.$person['name'].'"/></td>';
echo '<td><input type="text" class="form-control" name="login" id="'.$person['id'].'" placeholder="Login" value="'.$person['login'].'"/></td>';
echo '<td><input type="text" class="form-control" name="mail" id="'.$person['id'].'" placeholder="Mail" value="'.$person['mail'].'"/></td>';
echo '<td><input type="text" class="form-control" name="role" id="'.$person['id'].'" placeholder="Role" value="'.$person['role'].'"/></td>';
echo '<td><input type="text" class="form-control" name="group" id="'.$person['id'].'" placeholder="Group" value="'.$person['group'].'"/></td>';
echo '<td><select type="text" class="form-control" name="LoftID" id="'.$person['id'].'" placeholder="Loft">';
foreach($lofts as $info) {
if($info['id']==$person['LoftID']){
echo '<option value='.$info["id"].' selected>'.$info["name"].'</option>';
}
else{
echo '<option value='.$info["id"].'>'.$info["name"].'</option>';
}
}
echo '</select></td>';
echo '<td><button type="submit" name="update" value="'.$person['id'].'" class="btn btn-primary">Update</button></td>';
echo '<td><button type="submit" name="delete" value="'.$person['id'].'" class="btn btn-primary">Delete</button></td>';
echo '</tr>';
}
echo '</tbody></table>';
?>
</div>
</form>
What I need is for to allow me to pull the data from the $_POST so I can then throw it back into the database as an update based on the ID, which I believe I can do, as I have done that already in my code....
I would really like to do this without the need to display another page with the data on it to update....
Thanks in advance
You need Ajax for doing that job without reloading the page or go to another page with parameter. And remember that button doesn't has value like input. Use data-id or data-pid or what ever you like. And put a class name for example 'updateBtn' to identify the button.
echo '<td><button type="button" data-pid="'.$person['id'].'" class="btn btn-primary updateBtn">Update</button></td>';
<script>
$('.updateBtn').on('click', function() {
var pid = $(this).data('pid'); console.log(pid); // see the result in console
var pid = parseInt(pid); // change to int
$.ajax({
url: '/ajax/update-data/index.php', // specify folder and file name
data: { pid : pid },
dataType: 'json',
success: function (response) {
if(response.status == 'success') {
// do something to the html code to show the successful update
return false;
}
if(response.status == 'fail') {
// do something to the html code to show the fail update
return false;
}
}
});
});
</script>
Ajax file :
<?php
function response ($status) {
header("Content-Type:application/json");
$response['status'] = $status;
$json_response = json_encode($response);
echo $json_response;
}
if($_POST) {
$pid = filter_input(INPUT_POST, 'pid', FILTER_SANITIZE_NUMBER_INT);
if($pid) {
$done = // do php to chage update. You can refer to class or direct php mysql update
if($done) {
response ('success');
}else{
response ("fail");
}
}else{
response ("parameter fail");
}
}
?>
OK so I think I have found the answer, and have included the following;
echo '<form class="form-horizontal" action="" method="post">';
Just under the first foreach statement, so that each row is its own form element.
Does anyone see any issues with doing it this way?? The data will always be quite limited and likely to never be more than 10s of rows.
Kind regards and thanks for all the help

trouble appending/combining two variables

Here's my code, It's a forum, there are posts with dislike buttons,like buttons, and a text box for commenting with each individual post, check the screenshot below. I'm trying to put the $comments variable, which are the comments itself, at the end of $posts so it displays below the posts properly like the like buttons and comment box are displayed.
I'm trying to just get the comments displayed underneath the comment box. If I call displayComments(the function in $comments definition) in the for each loop then the comments get displayed separately from the posts I've tried combining the $comments at the end of $posts with this operator +, and I've tried making a new variable equal to the both of them. Here's the code(not the full file).
<?php
include("connect.php");
include("check.php");
include("Trying.php");
include("Comment.php");
if(isset($_POST['username'])){
if (isset($_POST['post'])) {
if ($_FILES['postimg']['size'] == 0)
{
$postbody = $_POST['postbody'];
$loggedInUserId = check::isLoggedIn();
if (strlen($postbody) > 160 || strlen($postbody) < 1)
{
die('Incorrect length!');
}
connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(),\'\',0,0)', array(':postbody'=>$postbody));
}
}
if (isset($_POST['comment'])) {
$postid = $_GET['postid'];
$commentbody = $_POST['commentbody'];
if (strlen($commentbody) > 160 || strlen($commentbody) < 1) {
die('Incorrect length!');
}
connect::query('INSERT INTO comments VALUES (null,:comment, NOW(), :postid)',array(':comment'=>$commentbody,':postid'=>$postid));
//}
}
$dbposts = connect::query('SELECT * FROM dry_posts ORDER BY id DESC');
$posts = "";
$comments = Comment::displayComments($p['id']);
foreach($dbposts as $p){
if (!connect::query('SELECT post_id FROM dry_likes WHERE post_id=:postid', array(':postid'=>$p['id']))) {
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
;
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
else{
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
}
?>
<form action='try.php' class = "forum" method="post" enctype="multipart/form-data">
<textarea name="postbody" rows="4" cols="60" class = "text"></textarea>
<br />Upload an image:
<input type="file" name="postimg">
<input type="submit" name="post" value="Post">
</form>
<div class="posts">
<?php echo $posts;
?>
</div>
Here's the function I'm calling in the $comments variable
public static function displayComments($postid)
{
$comments = connect::query('SELECT * FROM comments WHERE post_id=:postid',array(':postid'=>$postid));
foreach($comments as $comment)
{
echo $comment['comment']."<hr />";
}
}
I know this won't help a lot of people but I'm just not sure what to do, How do you suggest I get everything to display inline, should rearrange my code?

Check if <input> is empty or only whitespace

Some website's search boxes aren't very good: when you put a space in the search bar and submit, it returns every search item they have. (Example: http://watchfreemovies.unblocked.co/)
Mine does the same. What can I do to make it verify that there is actual text in the search box before submitting?
Search box and button:
<div class="Nava">
<input type="button" name="button" id="hello" value="M" />
</div>
<form action='/search.php' method='GET'>
<input id='searchbar' type='text' name='search' placeholder="search for movies & shows" maxlength="50" />
<input id='submit' type='submit' name='submit' value='Search' />
</form>
<div class="Navbuttons">
<input type="button" name="button" id="button" value="shows" />
<input type="button" name="button" id="button" value="movies" />
</div>
Results page:
$x = 0;
$construct = '';
$search = $_GET['search'];
$search = preg_replace("#[^0-9a-z ]#i", "", $search);
if (strlen($search) <= 0)
echo "Search term too short";
else {
echo "You searched for '<b>$search</b>' ";
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$search_exploded = explode(" ", $search);
foreach ($search_exploded as $search_each) {
$x++;
if ($x == 1)
$construct .= "keywords LIKE '%$search_each%'";
else
$construct .= "AND keywords LIKE '%$search_each%'";
}
$construct = "SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum == 0)
echo "<p>Sorry, there are no matching result for '<b>$search</b>'.</p>
<li> Try different words with similar
meaning</li>
<li> make sure you're spelling is correct</li>";
else {
echo "$foundnum results found !";
while ($runrows = mysql_fetch_assoc($run)) {
$title = $runrows['title'];
$desc = $runrows['description'];
$url = $runrows['url'];
echo "
<hr><a href='$url'><h2><b>$title</b></h2></a><br>
$desc<br>
<a href='$url'></a><p>
";
}
}
}
Check server-side:
if (!trim($_GET['search'])) {
echo 'Enter a query.';
}
Check client-side:
<form action='/search.php' method='GET'>
<input id='searchbar' type='text' name='search' placeholder="search for movies & shows" maxlength="50" required />
<input id='submit' type='submit' name='submit' value='Search' disabled />
</form>
<script>
document.getElementById('searchbar').onkeypress = function() {
document.getElementById('submit').disabled = !this.value.trim();
}
</script>
Fiddle

Basic PHP/MySQL INSERT INTO Multiple Tables from Forms

I am trying to make a simple PHP form submission and insert some data to MySQL, my tables are:
category: id, category_name
table1: category_id(FK), title,description
table2: table1_id(FK), filetype, filesize, filedate, filename
Form: Date, Title, description, category(drop down), upload file (get the file info like type, ext, size, filename)
Here is the code:
Form:
<strong>Fill up the form:</strong><br /><br>
<form enctype="multipart/form-data" action="upfileone.php" method="POST">
Date: <?php echo date("d-M-Y") ?>
<p>Title:
<input type="text" name="title" value="<?php echo $sel_filepage['file_title']; ?>" id="file_title" />
</p>
<p>Description:<br>
<textarea name="description" rows="4" cols="24">
<?php echo $sel_filepage['content']; ?></textarea>
</p>
Category:
<select name="select_cat">
<?php $cat_set = get_all_categs();
while($category = mysql_fetch_array($cat_set)){
$catname = $category['cat_name'];
echo '<option value="'.$catname.'">'.$catname.'</option>';
}
?>
</select>
<br><br>
<label for="file">Choose File to Upload:</label>
<input type="file" name="upfile" id="upfile" > <br /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="hidden" name="filepage" value="<?php echo $_GET['filepage']?>">
<input type="submit" name="upload" value="Add" class="pure-button pure-button-success">
Cancel
</form> <!-- END FORM -->
Action file:
<?php
require_once("includes/functions.php");
// directory to be saved
$target = "server/php/files/";
$target = $target . basename($_FILES['upfile']['name']);
// gets info from FORM
$currentDate = date("Y-m-d");
$file_title = $_POST['title'];
$content = $_POST['description'];
$category = $_POST['select_cat'];
$upfile = ($_FILES['upfile']['name']);
// connects to db
$con = mysqli_connect("localhost", "root", "password", "database");
if(mysqli_connect_errno())
{
echo "error connection" . mysqli_connect_error();
}
// insert to database
$sql = "INSERT INTO filepages (category_id,file_title,content)
VALUES ('$category','$file_title','$content')";
/*$sql2 = "BEGIN
INSERT INTO filepages (category_id, file_title, content)
VALUES ('$category','$file_title','$content')
INSERT INTO fileserv (file_date)
VALUES ($currentDate)
COMMIT";*/
if(!mysqli_query($con, $sql))
{
die('Error ' . mysqli_error());
}
echo "1 File Added <br>";
if (file_exists("server/php/files/" . $_FILES["upfile"]["name"]))
{
echo $_FILES["upfile"]["name"] . " already exists. ";
}
else
{
insertFile( $_POST['filepage'],
$_FILES["upfile"]["type"],
($_FILES["upfile"]["size"] / 1024),
$_FILES["upfile"]["name"]);
move_uploaded_file($_FILES["upfile"]["tmp_name"],"server/php/files/" . $_FILES["upfile"]["name"]);
echo "The FILE " . basename($_FILES['upfile']['name']) . " has been uploaded.<br>";
echo "Stored in: " . "server/php/files/" . $_FILES["upfile"]["name"] . "<br>";
echo "Upload: " . $_FILES["upfile"]["name"] . "<br>";
echo "Type: " . $_FILES["upfile"]["type"] . "<br>";
echo "Size: " . ($_FILES["upfile"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["upfile"]["tmp_name"] . "<br>";
}
?>
It does insert to both tables, now my main problem is how to get the ID from drop down menu of category and insert to Filepages.category_id.
How can I get the Filepages.ID data and insert it to Fileserve?
So you want the ID of the inserted row.
You can simply use the following php function http://www.php.net/manual/en/mysqli.insert-id.php
This question should nonetheless be moved to stackoverflow

Joomla 1.5 Database Query example needed

I have made a query, using mysql_* way, that select's some values from a table, where row's id is 1. Then I put all those values in variables so I can echo them in to my form. How can I do the same thing using Joomla's database query way ?
Here is an example of my code that working, using mysql_*:
<?php // DATABASE QUERY
$query="SELECT countdown_module, hometeam_header
FROM jos_gm_nextmatch
WHERE id = 1";
$result=mysql_query($query);
// DATABASE VARIABLES
$countdown_module = mysql_result($result,$i,"countdown_module"); ?>
$hometeam_header = mysql_result($result,$i,"hometeam_header"); ?>
<form action="" method="post" name="form">
<input name="countdown_module" value="<?php echo $countdown_module ?>" type="text" />
<input name="hometeam_header" value="<?php echo $hometeam_header ?>" type="text" />
<input name="submit" type="submit" value="UPDATE" />
</form>
OK I found it!!! Here is an example...
<?php // DATABASE QUERY
$db = JFactory::getDBO();
$query="SELECT countdown_module, hometeam_header
FROM jos_gm_nextmatch
WHERE id = 1";
$db->setQuery($query);
$rows = $db->loadObjectList();
$itemrow = $rows[0];
// DATABASE VARIABLES
$countdown_module = $itemrow->countdown_module;
$hometeam_header = $itemrow->hometeam_header; ?>
<form action="" method="post" name="form">
<input name="countdown_module" value="<?php echo $countdown_module ?>" type="text" />
<input name="hometeam_header" value="<?php echo $hometeam_header ?>" type="text" />
<input name="submit" type="submit" value="UPDATE" />
</form>