Trouble with a php post back solution - php

This may be an easy fix, but I can't get my head around it .
Basically I've remade my blog using a database and php rather than wordpress.
I want my site to show the most recent post first, then i'm using PhP postback to alter it
So far it works, but i can't figure out a way for it to automatically go to the most recent one but then change after the postback.
<?php
$inId = $data[0];
//if (!empty($inId))
//{
//}
//else
//{
//$inId = $_POST['ID'];
//}
include 'Includes.php';
$blogPosts = GetBlogPosts($inId);
foreach ($blogPosts as $post)
{
echo "<div class='post'>";
echo "<h3>" . $post->title . "</h3>";
echo "<p2>" . $post->post . "</p2>";
echo "<span class='footer'>Posted By: " . $post->Author . " Posted On: " . $post- >datePosted . "</span>";
}
echo '<form name="myForm" action="Index.php" onsubmit="return validateFormStrings()" method="post">';
echo'<select name ="ID">';
$query4 = "SELECT * FROM Blogs ORDER BY ID ";
$result = mysql_query($query4);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<option value="'.$row['ID'].'">'.$row['Title'].'</option>';
echo '<br>';
}
echo'</select>';
echo '<input type="submit" value="Retrieve Posts">';
echo '<a href="Index.Php" ></a>';
echo '</form>';
?>
As you see i tried to fiddle with !empty and things but that's not really what im trying to do.
If i'm unclear let me know.
I almost need something like " if ( button !pressed) then its data[0] else its the postback
Thanks in advance

I found out how to do it using the isset() function.
if (isset($_POST['submit1']))
{
$inId = $_POST['ID'];
}
else
{
$inId = $data[0];
}
This checks if the submit button has doe the postback or not. Works a treat.
Gonna have a go at trying it with Ajax so I don't need the button at all ^^

Related

Put results in different divs depending on what comes out of the database?

How it looks:
https://jsfiddle.net/jef2L8m6/
How it should look:
https://jsfiddle.net/jef2L8m6/1/
I know it looks really bad, this is just for testing purposes only.
Some of the Backend Code:
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>You are not registered (Or there are no messages to display)</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
echo "<div class='msg_user'>";
echo "<div class='username_user'><span>" . $row['username'] . "</span></div>";
echo "<div class='message_user'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "";
mysqli_close($con);
?>
Thank you so much for taking your time to read this.
I am trying to figure out how I would change the div tags of each separate user depending on their name?
Is there any way to do this using PHP, I have tried doing 2 separate query's of one that selects just the users messages and another that selects everyones (excluding the users)
But none of them worked due to it not ordering them correctly.
Could I somehow change the div's using PHP if the username that comes out is not equal to the username in the session?
Thank's so much, if you don't think I explained this very well please give me some feedback and I will change/add what you need, THANK YOU!
Thank you so much "u_mulder", you have been very helpful in making me think of a simple way to solve this problem.
I was thinking way too complex for something so simple!
Here is the final code for anyone who this may help:
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
while($row = mysqli_fetch_array($result)) {
$class = 'msg';
if ($row['username'] == $_SESSION['name']) {
$class = 'msg_user';
}
echo "<div class='" . $class . "'>";
// other codes here
}

Strange behaviours on PHP MYSQL image unlink

I have followed several tutorials on here and I can't figure out my mistake.
The Gallery gets displayed correctly, and the check boxes have the right value when I check with Element inspector in Firefox, but this little script I wrote always unlinks the last picture in the loop, and the Database row does not get deleted.
Maybe you have a better eye for what I am missing then myself?
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<form action='' method='post'>
<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
if (isset($_POST['delete']) && is_array($_POST['delete']) && count($_POST['delete']) > 0) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $photo_filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $photo_filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $photo_filename");
}
?>
You're opening the element each time for the new photo, but the submit button and only one closing tag are outside all of the forms. You may want to fix the html to have this working properly.
EDIT:
The wrong file gets deleted, because you're using $photo_filename variable in the last 3 rows instead of the value from $_POST['delete'].
Side note: this code is really awful and buggy. It's a security nightmare.
something like this should sort it, I have not tested it but hopefully it will work.
foreach ($_POST['delete'] as $filename) {
unlink("THIS/IS/A/WORKING/PATH/houses/" . $filename);
unlink("THIS/IS/A/WORKING/PATH/houses/tb_" . $filename);
mysql_query("DELETE FROM gallery_photos WHERE photo_filename = $filename");
}
echo '<form action='' method='post'>';
$sql = "SELECT id, title FROM houses ";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
echo $result['title'] . $result['id'];
echo"<br>";
$sql1 = "SELECT * FROM gallery_photos WHERE photo_category=" . $result['id'];
$query1 = mysql_query($sql1);
while ($row = mysql_fetch_array($query1)) {
$photo_filename = $row['photo_filename'];
echo "<li style='float:left; list-style-type:none;'>
<img src='houses/" . $photo_filename . "' title='$photo_filename' width='100px'>
<input type='checkbox' name='delete[]' value='$photo_filename'/> <br>
</li> ";
}
echo "<p style='clear:both' /> <input type='submit' value='Delete Selected' />";
echo" </form>";
echo "<p style='clear:both;'>";
echo "<br><br>";
}
notice the [] at the end of the checkbox name, this means that it will create an array of them. You might want to add an additional check around the foreach to prevent it running if the $_POST['delete'] has not been set.
First, just to be sure, you are getting the params, you can use:
echo "<br />Contents of \$_POST:<br />";
foreach ($_POST as $k => $v) {
echo " $k = $v<br />";
}
So you know what params are you getting. And it looks like working.
Also, you can use it, to delete the images,
foreach ($_POST as $k => $v) :
if ( $k == "delete" ) :
// add your code for unlink and delete
endif;
endforeach;
Second, check for permissions before to delete
chmod($this->uploaddir . $this->finalName, octdec(0777)); // Maybe 0666 is enough
#unlink( path_to_file ); // # to avoid see code errors
And just, for you consideration, maybe if you use you don't have to be taking care about float, and clearing
Cheers

Mysql Field Data not displaying when a link is clicked?

I'm trying to get data from a database if a link is clicked.
I used the example codes suggested from this example -Getting mysql field data when a link is clicked?
But it doesn't work when I click on a link nothing comes up.
main.php
<?php
include('conn.php');
$sql2 = "SELECT Title FROM addpromo";
$result2 = mysql_query($sql2);
echo "<div id=\"links\">\n";
echo "<ul>\n";
while ($row2 = mysql_fetch_assoc($result2)) {
echo "<li> <a href=\"fullproject.php?title=\""
. urlencode($row2['Title']) . "\">"
. htmlentities($row2['Title']) . "</a>\n</li>";
}
echo "</ul>";
echo "</div>";
?>
This is displaying correct.but when I click at a link nothing is showing up in fullproject.php, Just a blank page.
fullproject.php
<?php
// Connect to server.
include('conn.php');
$projectname = isset($_GET['Title']);
$sql1 = "SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1 = mysql_query($sql1);
while ($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title'] . "<br />";
echo "<br /> ";
}
?>
Can someone help me to fix this, or any other way to make this(to get data from a database if a link is clicked) possible?
Change to this
main.php
<?php
include('conn.php');
$sql2="SELECT Title FROM addpromo";
$result2=mysql_query($sql2);
echo '<div id="links">';
echo '<ul>';
while($row2 = mysql_fetch_assoc($result2)){
echo '<li>'.htmlentities($row2['Title']).'</li>';
}
echo '</ul>';
echo '</div>';
?>
fullproject.php
<?php
if(isset($_GET['title'])){
include('conn.php');
$projectname= $_GET['title'];
$sql1="SELECT Title FROM addpromo WHERE Title = '$projectname'";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_assoc($result1)) {
echo "Project Name: " . $row1['Title']. "<br />";
echo "<br /> ";
}
}
?>
This is storing a boolean value $projectname= isset($_GET['Title']);, whether or not the title is set. Instead use $projectname = $_GET['Title'];
isset returns a boolean value (true/false) and you want the actual value of the variable:
$projectname= $_GET['title'];
Furthermore, you have to pass only the title as the URL parameter, without enclosing it within quotes. So there is an error in this line:
echo "<li> <a href=\"fullproject.php?title=" . urlencode($row2['Title']) . "\">"
Note the lack of \" after title=

Passing a value through URL

Here is what i want to achieve ; sending ID's through URL's and printing it.
index.html
ID 1
ID 2
receive.php
<?php
$id_q = $_GET['id'];
print "The parameters passed through URL are $id_q";
?>
This above code works perfectly, I'm not able to do this with a list of ID's printed with a php command.
The below code is used to print all the PID's in the DB.How do i make every PID printed clickable ?
When I add html tags inside PHP code it throws up an error.
print.php
$result = mysqli_query($con,"SELECT * FROM List");
while($row = mysqli_fetch_array($result))
{
echo $row['PID'];
}
edit-query.php
$pid_q=$_GET[pid];
echo $pid_q;
while($row = mysqli_fetch_array($result))
{
echo "<a href='receive.php?id=".$row['PID']."'>".$row['PID']."</a>";
}
If you want to add your own text to a variable or echo, quote it and separate the variable with a "."
echo ''.$row['PID'].'';
you should do that like this
How about...
echo '' . $row['PID'] . '';
I believe this is what you mean?
while($row = mysqli_fetch_array($result))
{
echo 'Print ID: ' . $row['PID'] . '';
}
while($row = mysqli_fetch_array($result))
{
echo "<p id=".$row['PID']." class='clickable'>" . $row['PID'] . "</p>";
}
$(document).ready(function(){
$("#clickable").click(function(){
$(this)...something...
});
});
This is a little something you can do using JQuery if you wanted each PID to do something other than refer to another location. It will listen on any with the clickable class.

How to stop search field returning all results when submitting empty search field?

If i click on my search field and submit it without entering any text all the data in my database is returned. How is this stopped so nothing happens?
Check out the site:
weezy.co.uk/newresults.php
Thanks!
James
<?php
$conn = mysql_connect("cust-mysql-123-02", "uwee_641290_0001", "La0%-Mr4");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("weezycouk_641290_db1")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br>';
echo '<br>';
echo '<div class="data1">';
echo $row["name"];
echo '</div>';
echo '<br>';
echo '<div class="data2">';
echo $row["lastname"];
echo '</div>';
echo '<br>';
echo '<div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
you should check if it's empty before making a query:
if(empty($_POST['searchterm'])){
//don't search and show an error message
}else{
//proceed as normal, do the query
}
otherwise you might end up making a query like:
WHERE name LIKE('%%')
which is really expensive and returns all your database rows
Best way to do this (imo) is to have a simple javascript checking if the input is blank or not.
It is always wise to do some front end using javascript/Jquery. form validation where you are prompting users to input something.
Once you are done you may also check on the back end using the following:
if(isset($_POST['searchterm'])){
// search for the results.
}else{
// do nothing or show proper message
}
I think the best way would be to disable the submit button on the client side whenever your search box is empty.
You could do something like:
$(document).ready(function()
{
$('#searchBox').keyup(function()
{
if($(this).val() == '')
{
$('#searchButton').attr('disabled', true);
}
else
{
$('#searchButton').removeAttr('disabled');
}
});
});
where your html is like:
<input type='text' id="searchBox" />
<input type='button' id='searchButton' value='search' disabled/>
Make sure to validate on the server side as Nicola has indicated.
I was facing some problems in the above code. So the following improved version of the above code works just fine:
<form action="searchengine.php" method="POST">
<input type="text" id = "searchbox" name="searchterm" placeholder="Search here">
<input type="submit" id = "searchbutton" value="Search" style="display:none;">
</center>
<script src="http://codeorigin.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#searchbox').keyup(function()
{
if($(this).val() == '')
{
$('#searchbutton').hide();
}
else
{
$('#searchbutton').show();
}
});
});
</script>

Categories