Delete using PHP is not working - php

I am having a rather strange issue and for the likes of me, cannot figure it out!
Basically, I have users who are allowed to upload documents, which are then associated with their profile.
If the user decides to delete a document, the only thing that gets deleted here, is the document, but not the content included, e.g. comments, title, etc - it's as if nothing ever happened - except of course - the physical document has been deleted - sql entries however have not.
mydocs.php:
if ($_SESSION['USERID'] != "" && $_SESSION['USERID'] >= 0 && is_numeric($_SESSION['USERID']))
{
if($_REQUEST['submitdelete']!="")
{
$deletedoc = $_POST['deletedoc'];
$svcount = count($deletedoc);
for ($i = 0; $i < $svcount; $i++)
{
if ($deletedoc[$i] != "" && $deletedoc[$i] >= 0 && is_numeric($deletedoc[$i]))
{
$query = "SELECT * FROM docs WHERE DID='".mysql_real_escape_string($deletedoc[$i])."'";
$executequery = $conn->execute($query);
$theuserid = $executequery->fields['USERID'];
$doc_name = $executequery->fields['doc_name'];
if(mysql_affected_rows()>=1)
{
$docpath = $config['docdir']."/".$doc_name;
#chmod($docpath, 0777);
if (file_exists($docpath))
{
#unlink($docpath);
}
if($theuserid == $_SESSION['USERID'])
{
$deletefrom[] = "docs";
$deletefrom[] = "docs_comments";
$deletefrom[] = "docs_favorited";
for($j=0;$j < count($deletefrom);$j++)
{
$query = "DELETE FROM ".$deletefrom[$j]." WHERE DID='$deletedoc[$i]'";
$conn->Execute($query);
}
$tempthumbs = $config['thumbdir']."/".$deletedoc[$i].".jpg";
if(file_exists($tempthumbs))
{
#unlink($tempthumbs);
}
if ($svcount > 1)
{
$message = $lang['643'];
}
else
{
$message = $lang['644'];
}
}
else
{
if ($svcount > 1)
{
$error = $lang['645'];
}
else
{
$error = $lang['646'];
}
}
}
}
}
}
mydocs.tpl:
<form id="deleteform" name="deleteform" action="{$baseurl}/mydocs.php" method="post">
{section name=i loop=$docs}
{insert name=seo_clean_titles assign=title value=a title=$docs[i].title}
<div class="column {if $smarty.section.i.iteration % 6 == 0}last{/if}">
<div class="image"><img src="{$vthumburl}/{$docs[i].doc_name|truncate:-4:"":true}.jpg" alt="{$docs[i].title|stripslashes|truncate:25:"...":true}" ></div>
<h3>{$docs[i].title|stripslashes|truncate:17:"...":true}
<br />{$lang485}: <input type="checkbox" name="deletedoc[]" value="{$docs[i].DID}">
<br />{$lang318}</h3>
</div>
{/section} <div class="btndelete">
<input type="submit" value=" " name="submitdelete"></div>
</form>
Urgently awaiting a solution / assistance.
Many thanks in advance!

There is nothing wrong with the code.
For some reason, the connect.php was using write only permissions to the sql db.
Change it to All Privileges and now it works.
Now to secure it.

Related

How to make if cond on exact count?

I use PHP and ODBC, and I was wondering how to make if condition for an exact number...?
$DB = $core_db->Execute("SELECT TOP (10) ID, Name, Age, Location FROM Profiles ORDER BY Name");
$num=0;
while(!$DB->EOF){
if ($DB->fields[0] != 0) {
echo'<div class="ID">'.++$num.'</div>
<div class="name">'.$DB->fields[1].'</div>
<div class="name">'.$DB->fields[2].'</div>
<div class="name">'.$DB->fields[3].'</div>
';
}
$DB->MoveNext();
Now I want to use if with echo'<div class="ID">'.++$num.'</div> to stylize first 3 profile but I don't know how!
I tried
if ($num === 1){
echo'<div class="ID">1*</div>';
} else {
echo'<div class="ID">'.++$num.'</div>';
}
and it didn't work with me, it gave 1* to all rows not first one only.
$DB = $core_db->Execute("SELECT TOP (10) ID, Name, Age, Location FROM Profiles
ORDER BY Name");
$num=0;
while(!$DB->EOF){
if ($DB->fields[0] != 0) {
echo'<div class="ID">'.$num.'</div>
<div class="name">'.$DB->fields[1].'</div>
<div class="name">'.$DB->fields[2].'</div>
<div class="name">'.$DB->fields[3].'</div>
';
$num++;
}
$DB->MoveNext();
try this, here I'm incrementing your $num when it runs from each loop.
here I'm doing post-increment,
Keep it simple
if ($num == 1){
echo'<div class="ID">1*</div>';
$num = $num + 1;
} else {
echo'<div class="ID">'.$num.'</div>';
$num = $num + 1;
}

How to check if X has played and switch the turn to O

I just started learning PHP # school and for the third assignment we have to create a TicTacToe game. I have followed a turorial video on youtube and have made a game that is playable at the moment. But it doesnt know whos turn it is. IE: you can keep pressing the submit button and the computer will keep filling in O's without the player to have to fill in a X.
Please can someone explain how i can make the script know who's turn it is?
I want to know the logic behind it. So only a code wont help me at all, please explain how you check if the player has filled in a X before you switch turn for instance.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Boter, Kaas & Eieren</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
$winner = 'niemand';
$box = array('','','','','','','','','');
if (isset($_POST["submit"])){ //When the player hits submit, we retrieve the data
$box[0] = $_POST['box0'];
$box[1] = $_POST['box1'];
$box[2] = $_POST['box2'];
$box[3] = $_POST['box3'];
$box[4] = $_POST['box4'];
$box[5] = $_POST['box5'];
$box[6] = $_POST['box6'];
$box[7] = $_POST['box7'];
$box[8] = $_POST['box8'];
//print_r($box); //kijken in welke array, wat is ingevuld
//check if the player has won
if (($box[0]=='x' && $box[1]=='x' && $box[2]=='x') ||
($box[3]=='x' && $box[4]=='x' && $box[5]=='x') ||
($box[6]=='x' && $box[7]=='x' && $box[8]=='x') ||
($box[0]=='x' && $box[4]=='x' && $box[8]=='x') ||
($box[2]=='x' && $box[4]=='x' && $box[6]=='x') ||
($box[0]=='x' && $box[3]=='x' && $box[6]=='x') ||
($box[1]=='x' && $box[4]=='x' && $box[7]=='x') ||
($box[2]=='x' && $box[5]=='x' && $box[8]=='x')){
$winner = 'x';
echo "Speler wint";
}
//check if X has played and switch turn to O
$blank = 0; //assume there is no empty box
//check for an empty box
for ($i=0; $i<=8; $i++){
if ($box[$i]==''){
$blank=1;
}
}
//if there is an empty box and no winner yet its O's turn
if ($blank == 1 && $winner == 'niemand'){
$i = rand(0,8);
while ($box[$i]!=''){ //keep looking for an empty box if $i isnt empty
$i = rand(0,8);
}
$box[$i] = "o";
//check if O has won
if (($box[0]=='o' && $box[1]=='o' && $box[2]=='o') ||
($box[3]=='o' && $box[4]=='o' && $box[5]=='o') ||
($box[6]=='o' && $box[7]=='o' && $box[8]=='o') ||
($box[0]=='o' && $box[4]=='o' && $box[8]=='o') ||
($box[2]=='o' && $box[4]=='o' && $box[6]=='o') ||
($box[0]=='o' && $box[3]=='o' && $box[6]=='o') ||
($box[1]=='o' && $box[4]=='o' && $box[7]=='o') ||
($box[2]=='o' && $box[5]=='o' && $box[8]=='o')){
$winner = "o";
echo "KI wint";
}
}
//check if it is a draw
if ($blank == 0 && $winner == 'niemand'){
echo "Gelijkspel!";
}
}
?>
<div id="beurt">
<p>
<form action="destroy.php" method="get">
<input type="submit" id="destroy" onClick="windows.location.href'index.php'" value="Begin opnieuw!">
</form>
</p>
</div>
<form id="game" name="tictactoe" method="post">
<?php
//create the grid to play
for ($i=0; $i<=8; $i++){
echo "<input class=\"box\" type=\"text\" name=\"box$i\" value=\"$box[$i]\">";
if ($i==2||$i==5||$i==8){ //put in a break if $i is 2,5 or 8
echo "<br>";
}
}
if ($winner == 'niemand'){
echo "<br><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Spelen!\"><br></form>";
}
?>
</body>
</html>
Please help me out.
You can add a new variable $_POST['player'] which you can change from 0 to 1 or from 1 to 0 and that way know by the value which player should play now.
I'm not going to write you the code since I gave you a hint how it should be done and you have to learn by yourself :)
I would add a small txt file to save how was the last one to play.
For instance you could save many diffrent values into a single .txt file like this.
<?php
function savesettings($nextturn){
if(is_file("file.txt")){
$mysettings = unserialize(file_get_contents("file.txt"));
}else{
$mysettings = array();}
$mysettings["nextturn"]=$nextturn;
file_put_contents("file.txt",serialize($mysettings));
}
function loadsettings(){
if(is_file("file.txt")){
$mysettings = unserialize(file_get_contents("file.txt"));
}else{
$mysettings = array();
}
return $mysettings["nextturn"];
}
?>
You can use the following code like this:
//Save name of next player
savesettings("David");
// Load the player setting
$player = loadsettings();

PHP page not loading generated value on first button click?

I have a single page php application to generate an 8 digit number, user inputs a value and page generates another value, both values are inserted into mysql db and displaying the generated value in an input box at a single button click. Insertion is happening, but generated value is not displaying in the inputbox at the first time, I also tried session its not helping too.
here is my php code,
<?php
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div>
<?php
if(isset($_POST['luckyButton']) && $_POST['myLuckyNumber'] != ""){
//sleep(20);
$myLuckyNum = $_POST['myLuckyNumber'];
$resultmyLuckyNum = mysql_query("SELECT * FROM lucky where luckyNum='$myLuckyNum'") or die(mysql_error());
if (mysql_num_rows($resultmyLuckyNum) > 0) {
while ($rowmyLuckyNum = mysql_fetch_array($resultmyLuckyNum)) {
$generatedNumber = $rowmyLuckyNum["generatedNum"];
}
}else{
$gen = getGen();
$resultGenNum = mysql_query("INSERT INTO lucky (slno, luckyNum, generatedNum) VALUES ( NULL, '$myLuckyNum', '$gen')");
if (mysql_num_rows($resultGenNum) > 0) {
$generatedNumber = $gen;
}
}
}
?>
<form action="" method="post">
<input type="text"class="inputs" name="myLuckyNumber" onClick="this.select();" placeholder="Enter You Lucky Number" value="<?php echo $myLuckyNum; ?>" />
<input type="submit" class="css_button" name="luckyButton" value="Check"/>
</form>
</div>
<br><br><br>
<?php
if($generatedNumber != ""){
echo '<input type="text" name="myLuckyNumber" onClick="this.select();" id="generatedNumber" readonly="true" value="' . $generatedNumber . '" />';
}
echo '<p id="errText"> ' . $err . ' </p>';
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
function getGen(){
$gen1 = random_string(8);
$result = mysql_query("SELECT * FROM lucky where generatedNum='$gen1'") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
if($row["generatedNum"] == $gen1){
getGen();
}
}
}else{
//echo $gen1;
return($gen1);
}
}
?>
</body>
</html>
my table,.
CREATE TABLE `lucky` (
`slno` int(11) NOT NULL,
`luckyNum` text NOT NULL,
`generatedNum` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
The problem with your code is that mysql_num_rows will return either 0 or 1, use it like
if($resultGenNum === 1){
$generatedNumber = $gen;
}
You are using mysql_num_rows in a wrong way. When you run insert query, it does not return rows, it returns true or false (Boolean). When it will return true, you will get 1 (as $resultGenNum).
use this instead:
if ($resultGenNum === 1){
$generatedNumber = $gen;
}
Instead of using if ( $generatedNumber != "" ), perhaps you should try something like if ( isset( $generatedNumber ) ).
If $generatedNumber doesn't exist (which it doesn't if nothing was posted to the script), then the comparison will fail (in fact, you're probably getting a PHP error).
Of course, that leads us to the next problem - if nothing is posted to the script, you don't generate a number. So of course, if you don't generate a number, there is no number to display. So you should structure your code in such a way that a random number is always generated - regardless of whether a post variable was received or not.

how can I dynamically add DIV class="clear" after every third result when fetching DB when exist

I am kinda lost with what I am trying to achieve here, really need some help with the following.
While fetching DB using script provided below, I need to add <div class="clear"></div> after every third occurrence and if it is less than 3, lets say 2 or even one and there is no more after that after that last one.
Here is my script
<?
$template_query = 'SELECT * FROM Files WHERE parentpageID = :id and show_in_category = "1" ORDER BY ID asc';
$res = $db->prepare($template_query);
$res->execute(array(':id' => $current));
$add_rowNum = 0;
while ($info = $res -> fetch()){
$add_rowNum++;
$templateTitle = $info['templateTitle'];
$add_refering_url = $info['referring_url'];
$templ_link = $category_folder.$add_refering_url;
$teaserText = $info['teaserText'];
$path_to_add_images = $image_path.$info['ImagePath'].DS;
$add_img_info = $path_to_add_images.$info['templateImage'];
$add_img_alt && $add_img_title && $templateTitle = $info['templateTitle'];
list($width, $height, $type, $attr) = getimagesize($add_img_info);
$last_class = ($add_rowNum == $res->rowCount()) ? 'frame' : 'frame frame_margin';
print<<<END
<div class="$last_class">
<div class="prod">
<div class="title"><a href="$templ_link">$templateTitle
<img src="$add_img_info" alt="$add_img_alt" $attr title="$add_img_title"></a>
</div>
</div>
<div class="prd">
$teaserText
</div>
</div>
END;
}
?>
your help is highly appreciated
Use below code:
If(($add_rowNum % 3) == 0) {
echo "<div class='clear'></div>";
}
Add this code after the END syntax.
Using with %
if ($add_rowNum % 3 == 1)
echo '<div class="clear"></div>';
Try this. I think this logic will solve this problem!
$total_records = 10;
for($i=1;$i<=$total_records;$i++) {
echo "Hi";
if($i%3 == 0) {
echo "<br/>==================<br/>";
}
if(($i == $total_records) && ($total_records%3 != 0)) {
echo "<br/>==================<br/>";
}
}

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

Categories