Loop form in PHP, Submit all forms with 1 button - php

I have a question. I want to make a history timeline, on this timeline the user can add 'elements' (e.g. a element for each year.).
In form 1 the user creates timeline and says the amount of elements on the timeline this gets send to the database (this works).
In form 2 the user can fill the elements. (This doesnt work).
In form 1 (if someone wants 5 elements) after posting, the database creates 5 records (for each element one).
Now I want 5 different forms that fills these 5 elements (Title, description etc.), but with 1 submit button.
Now if i try this (see code below), only the 5th form gets posted...
How do I get this to work?
Thanks in advance,
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('classes/database.class.php');
$DB = Database::getInstance();
$titel = '';
$beschrijving = '';
$afbeeldingURL = '';
$jaar = '';
$element_id = '';
$velden = '';
$sql3 = "SELECT `id` , `aantal_elementen` FROM `tijdlijn` ORDER BY id DESC LIMIT 0, 1";
$last_id = $DB->_query($sql3);
if ($last_id->num_rows > 0) {
while($row = $last_id->fetch_assoc()) {
$last_id2 = $row["id"];
$aantal_elementen3 = $row["aantal_elementen"];
}
}
$sql4 = "SELECT * FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2."";
$sql5 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id ASC LIMIT 0,1";
$sql6 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id DESC LIMIT 0,1";
$sql7 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id ASC";
$last_id3 = $DB->_query($sql4);
$min_id = $DB->_query($sql5);
$min_id = mysqli_fetch_assoc($min_id);
$min_id = $min_id['id'];
$max_id = $DB->_query($sql6);
$max_id = mysqli_fetch_assoc($max_id);
$max_id = $max_id['id'];
$dingid[] = $DB->_query($sql7);
echo $min_id."</br>";
echo $max_id."</br>";
$current_id = $min_id;
if (isset($_POST) && !empty($_POST)) {
$boolError = false;
foreach ($_POST as $k => $v) {
$_POST[$k] = trim($v);
}
if (!isset($_POST['titel']) || trim($_POST['titel']) == '') {
$titel = 'error';
$boolError = true;
}
if (!isset($_POST['beschrijving']) || trim($_POST['beschrijving']) == '') {
$beschrijving = 'error';
$boolError = true;
}
if (!isset($_POST['afbeeldingURL']) || trim($_POST['afbeeldingURL']) == '') {
}
if (!isset($_POST['jaar']) || trim($_POST['jaar']) == '') {
$jaar_start = 'error';
$boolError = true;
}
if (
!isset($_POST['element_id'])
|| trim($_POST['element_id']) == ''
|| !preg_match('/^\d+$/', $_POST['element_id'])
) {
$element_id = 'error';
$boolError = true;
}
if ($boolError === false) {
$sql = "UPDATE `elementen`
SET
`titel` = '" . $_POST['titel'] . "',
`beschrijving` = '" . $_POST['beschrijving'] . "',
`afbeelding_url` = '" . $_POST['afbeeldingURL'] . "',
`jaar` = '" . $_POST['jaar'] . "'
WHERE `id` = ".$_POST['element_id'].";
";
if ($DB->_query($sql)) {
//$current_id++;
//exit;
} else {
header('Location: ?oops2');
exit;
}
} else {
$velden = "Ff alles invullen he";
}
?> <p>Vul het formulier hier onder in voor de elementen en maak een tijdlijn!</p><?php
}
if ($last_id3->num_rows > 0) {
while($row2 = $last_id3->fetch_assoc()) {
$last_id4 = $row2["id"];
?>
<form class="form-nieuws" method="post">
</br></br>
<?php echo $last_id2; ?>
<?php echo $current_id; ?>
<input id="titel2" class="<?= $titel ?> form-control" type="text" placeholder="Titel tijdlijn" name="titel" value="<?= isset($_POST['titel']) ? $_POST['titel'] : '' ?>">
<br>
<textarea id="beschrijving2" class="<?= $beschrijving ?> form-control" rows="3" placeholder="Beschrijving over tijdlijn" name="beschrijving" value="<?= isset($_POST['beschrijving']) ? $_POST['beschrijving'] : '' ?>"></textarea>
<br>
<input id="afbeeldingURL2" class="<?= $afbeeldingURL ?> form-control" type="text" placeholder="URL voor afbeelding" name="afbeeldingURL" value="<?= isset($_POST['afbeeldingURL']) ? $_POST['afbeeldingURL'] : '' ?>">
<br>
<input id="jaar" class="<?= $jaar ?> form-control" type="text" placeholder="Start jaar tijdlijn" name="jaar" value="<?= isset($_POST['jaar']) ? $_POST['jaar'] : '' ?>">
<input id="element_id" class="<?= $element_id ?> form-control" type="text" placeholder="<?php echo $last_id4 ?>" name="element_id" value="<?= isset($_POST['element_id']) ? $_POST['element_id'] : '' ?>">
<div class="foutlabel">
<em class="<?= ($velden) ? 'error' : '' ?>"><?= ($velden) ? $velden : '' ?>
</em>
</div>
</br>
<?php $current_id++;}
} ?> <div class="gabutton">
<input type="submit" value="Creeer tijdlijn">
</div>
</form>

The best way is to have only one form with input for each elements. You generate each form input in function of your elements.
With this way, you only have one button and one call to send data to your server.
In server side, you just need to parse and check data and be carefull about number of element you send.

Related

How do I $_GET id and true before updating database

I don't really know how to explain my question, but I am in need. Of how to display warning before update into database.
example:
<?php
#Get id and yes before update waring code
if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo "retry";
}
exit();
}
$id = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
here is my full code where I am trying to display the warning before updating into database
<?php
include_once 'init.php';
$error = false;
// check if form is submitted
if (isset($_POST['book'])) {
$book = mysqli_real_escape_string($conn, $_POST['book']);
$action = mysqli_real_escape_string($conn, $_POST['action']);
if (strlen($book) < 6) {
$error = true;
$book_error = "booking code must be alist 6 in digit";
}
if (!is_numeric($book)) {
$error = true;
$book_error = "Incorrect booking code";
}
if (empty($_POST["action"])) {
$error = true;
$action_error = "pick your action and try again";
}
if (!$error) {
if (preg_match('/(check)/i', $action)) {
echo "6mameja";
}
if (preg_match('/(comfirm)/i', $action)) {
if (isset($_SESSION["user_name"]) && (trim($_SESSION["user_name"]) != "")) {
$username = $_SESSION["user_name"];
$result = mysqli_query($conn, "select * from users where username='$username'");
}
if ($row = mysqli_fetch_array($result)) {
$idd = $row["id"];
$username = $row["username"];
$id = $row["id"];
$username = $row["username"];
$ip = $row["ip"];
$ban = $row["validated"];
$balance = $row["balance"];
$sql = "SELECT `item_name` , `quantity` FROM `books` WHERE `book`='$book'";
$query = mysqli_query($conn, $sql);
while ($rows = mysqli_fetch_assoc($query)) {
$da = $rows["item_name"];
$qty = $rows["quantity"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll)) {
$pid = $prow["id"];
$price = $prow["price"];
$count = 0;
$count = $qty * $price;
$show = $count + $show;
}
}
if ($show < $balance) {
echo "you cant buy here";
exit();
} elseif ($show > $balance) {
$redut = $balance - $show;
#display the warning before updating into daase if (isset($_GET["acept"])) {
$acept = $_GET["acept"];
} else {
$acept = " ";
}
if ($acept == "update") {
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
$id = (int)$_GET["id"];
$query = mysqli_query($conn, "update users set balance='$redut' where id='$id'");
if ($query) {
echo " Successfull";
} else {
echo mysql_error();
}
exit();
}
$idd = (int)$_GET["id"];
echo "<div class='topnav'>System Warning</div><div class='msg'>Are You Sure ?</div><div class='gap'></div><div class='button'><a href='?acept=update&yes=true&id=$idd'><font color='red'>Yes</font></a> | <a href='user.php'>No</a></div>";
}
}
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
}
?>
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="booking">
<fieldset>
<legend>Check Booking</legend>
<div class="form-group">
<label for="name">Username</label>
<input type="text" name="book" placeholder="Enter Username" required value="<?php if($error) echo $book; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($book_error)) echo $book_error; ?></span>
</div>
<input type="submit" name="booking" value="Sign Up" class="btn btn-primary" />
<table><input type="radio" name="action" value="comfirm" <?php if(isset($_POST['action']) && $_POST['action']=="comfirm") { ?>checked<?php } ?>>
<input type="radio" name="action" value="check" <?php if(isset($_POST['action']) && $_POST['action']=="check") { ?>checked<?php } ?>> Check booking <span class="text-danger"><?php if (isset($action_error)) echo $action_error; ?></span>
</div></table>
I don't really know where am wrong with the code, but the expected warning before update do not display and the database is not updated. big thanks in advance.
if (isset($_GET["yes"]) & $_GET["yes"] == true) {
change this to
if (isset($_GET["yes"]) && $_GET["yes"] == 'true') {
servers take the GET method as a string. not boolean
I don't really get what kind of warning you are trying to display. If it is for a user you can use the print or echo function. It is possible to echo a block of html so:
echo '<div class=”warning-msg”><p>MY WARNING</p></div>'
will display the block. Only thing is the warning may not be in de correct place or time.
Or in js
echo ‘<script type="text/javascript">’
echo ‘alert(“message successfully sent”)’
echo ’</script>’
If the waring is for jou personal use the build in php error handeling handeling.
Here is a snippet for a query function using php.
Use:
$query = query("SELECT ... (SQL)", $variable);

How can i insert multiple values into database?

I'm trying to insert multiple values into my database, the values are from a jQuery script that generate a tags when you click space.
I tried to put a name on the tag, but it only insert into the database, the last tag, i want to insert all tags.
Here my code
<script type='text/javascript'>
$(window).load(function(){
function closer(){
$('#close').live('click', function() {
$(this).parent().remove();
});
}
$('#tags').keypress(function(e) {
if(e.which == 32) {
var tx = $('#tags').val();
if (tx) {
$(this).val('').parent().before('<li class="tags"><span><input type="hidden" value="'+tx+'" name="tags">'+tx+'</input></span><a style="cursor:pointer;" id="close">[x]</a></li>');
closer();
}
}
});
});
</script>
<?php
include(PATH_MODULE . '/joboffers/view/joboffers_view.php');
//add job offer function
function addjo(){
connect();
addjoview();
//check if the button was clicked
if (isset($_POST['add_jo'])){
if ($_POST['job_category']) {
$job_category = mysql_real_escape_string($_POST['job_category']);
$check1 = 0;
} else {
$check1 = 1;
}
if ($_POST['description']) {
$description = mysql_real_escape_string($_POST['description']);
$check2 = 0;
} else {
$check2 = 1;
}
if ($_POST['job_name']) {
$job_name = mysql_real_escape_string($_POST['job_name']);
$check3 = 0;
} else {
$check3 = 1;
}
if ($_POST['hiring_manager']) {
$hiring_manager = mysql_real_escape_string($_POST['hiring_manager']);
$check4 = 0;
} else {
$check4 = 1;
}
if ($_POST['tags']) {
$tags = mysql_real_escape_string($_POST['tags']);
$check5 = 0;
} else {
$check5 = 1;
}
if ($_POST['localization']) {
$localization = mysql_real_escape_string($_POST['localization']);
$check6 = 0;
} else {
$check6 = 1;
}
if ($_POST['attributes']) {
$attributes = mysql_real_escape_string($_POST['attributes']);
$check7 = 0;
} else {
$check7 = 1;
}
if ($_POST['contract_type']) {
$contract_type = mysql_real_escape_string($_POST['contract_type']);
$check8 = 0;
} else {
$check8 = 1;
}
if ($_POST['professional_exp']) {
$professional_exp = mysql_real_escape_string($_POST['professional_exp']);
$check9 = 0;
} else {
$check9 = 1;
}
//verify if all fields are right
if ($check1 == 0 && $check2 == 0 && $check3 == 0 && $check4 == 0 && $check5 == 0 && $check6 == 0 && $check7 == 0 && $check8 == 0 && $check9 == 0){
$query =("INSERT INTO job_offers (job_category, description, job_name, hiring_manager, tags, localization, attributes, contract_type, profissional_experience) VALUES ('" . $job_category . "','" . $description . "','" . $job_name . "','" . $hiring_manager . "','" . $tags . "', '" . $localization . "', '" . $attributes . "', '" . $contract_type . "', '" . $professional_exp . "')");
db_query($query, '+');
echo "Congratulations! You have been successfully registered in our system.";
} else {
echo "Ops, something went wrong!";
}
}
}
?>
HTML
<form method="POST">
<br>
<label>Job category</label>
<input type="text" name="job_category" maxlength="100" >
<br><br>
<label>Description</label>
<textarea cols="22" rows="3" name="description"></textarea>
<br><br>
<label>Job name</label>
<input type="text" name="job_name" maxlength="130" >
<br><br>
<label>Hiring manager</label>
<input type="text" name="hiring_manager" maxlength="130" >
<br><br>
<label>Tags</label>
<div id="wrapbox">
<div id="box">
<input type="text" id="tags" class="tagstype" maxlength="230">
</div>
</div>
<br><br>
<label>Localization</label>
<input type="text" name="localization" maxlength="130" >
<br><br>
<label>Attributes</label>
<input type="text" name="attributes" maxlength="130" >
<br><br>
<label>Contract type</label>
<input type="text" name="contract type" maxlength="130" >
<br><br>
<label>Professional experience</label>
<input type="text" name="professional_exp" maxlength="130" >
<br><br>
<input name="add_jo" type="submit" />
</form>
Try changing this
<input type="hidden" value="'+tx+'" name="tags">
to this
<input type="hidden" value="'+tx+'" name="tags[]">
Then, in your PHP code, do something like this
if ($_POST['tags']) {
$tags = mysql_real_escape_string(implode(",", $_POST['tags']));
$check5 = 0;
} else {
$check5 = 1;
}
That will insert a comma-separated list of the tags into your tags field in your table. If you would rather have it be space-separated, simply use implode(" ", $_POST['tags']) instead.
That being said, I would suggest restructuring your database so that you do not have a tags column in your job_offers table. Instead, you would have a job_offer_tags table which would have the columns id, job_id and tag, and you only enter single tags into the tag column.

INSERT a row per array object

I am in the process of creating a document association tool whereby users can associate documents to a ticket from a pre-existing list of documents.
Thanks to the help of Alberto Ponte I was able to construct the initial radio box system (originally checkbox, changed for obvious reasons) from this question: Separate out array based on array data
Now that I have the radio buttons presenting correctly I am trying to get the data inserted into a MySQL with a row for each document. Following on from this I want to have it look up the table for each object and see if there is an existing entry and update that rather than inset a duplicate entry.
Apologies in advance for the soon to be depreciated code and I will be correcting the code going forward, however that is a much bigger task than I currently have time for.
Also apologies if the code is considered messy. I'm not fantastic at PHP and not too hot on best practices. Any quick pointers are always welcome.
Display code:
<?php
include "../includes/auth.php";
include "../includes/header.php";
## Security ########################################################
if ($company_id != 1 OR $gid < 7) {
echo' <div class="pageheader">
<div class="holder">
<br /><h1>Access Denied <small> Your attempt has been logged</small></h1>
</div>
</div>
';
exit();
}
// GET Values ###################################################
$jat_id = intval($_GET['id']);
$div_id = intval($_GET['div_id']);
## Page Start ########################################################
echo '
<div class="pageheader">
<div class="holder">
<br /><h1>Clovemead Job Management Platform<small> Welcome...</small></h1>
</div>
</div>
<div class="well5" style="width:1000px !important;">
<h3>Create Document Association</h3>
<table border=1>
<tr>
<td align=center><p>Here you can associate documents to Jobs and Tasks to.</p> </td>
</tr>
</table>';
$order2 = "SELECT * FROM documents";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
}
echo '
<h3>Documents</h3>
<table border=1>
<tr><th>Document Name</th><th>Document Type</th><th>Required</th><th>Optional</th><th>Not Required</th></tr>
';
$order2 = "SELECT * FROM documents ORDER BY type_id";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$nice_name = $row2['nice_name'];
$doc_id = $row2['id'];
$doc_type_id = $row2['type_id'];
echo '
<tr>
<td>'.$nice_name.'</td>';
$order3 = "SELECT * FROM document_types WHERE id = '$doc_type_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type_name = $row3['type_name'];
echo '
<td>'.$type_name.'</td>
<form method="post" action="create-doc-assoc-exec.php">
<input type="hidden" value="'.$doc_id.'" name="doc_id">
<input type="hidden" value="'.$jat_id.'" name="jat_id">
<input type="hidden" value="'.$div_id.'" name="div_id">';
$order4 = "SELECT * FROM document_assoc WHERE doc_id = '$doc_id'";
$result400 = mysql_query($order4);
$_results = mysql_fetch_array($result400);
if (!$_results) {
echo '
<td><input type="radio" name="req0" value="2"></td>
<td><input type="radio" name="req0" value="1"></td>
<td><input type="radio" name="req0" value="0" checked ></td>';
} else {
foreach ($_results as $result400) {
$requirement = $_results['requirement'];
}
$name = "req".$doc_id;
echo '
<input type="hidden" value ="'.$name.'" name="name">
<td><input type="radio" name="'.$name.'" value="2" '; if ($requirement == 2) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="1" '; if ($requirement == 1) { echo ' checked '; } echo '></td>
<td><input type="radio" name="'.$name.'" value="0" '; if ($requirement < 1) { echo ' checked '; } echo '></td>';
}
}
echo '
</tr>';
}
echo '
</table>
<input type="submit" name="submit value" value="Create Document Association" class="btn success Large"></form>';
$order2 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$dbname = $row2['division_dbname'];
$order3 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result3 = mysql_query($order3);
while ($row3 = mysql_fetch_array($result3)) {
$type = $row3['type'];
$type2 = strtolower($type);
echo '
<input type="button" value="Back" onclick="window.location='./view-'.$type2.'.php?id='.$jat_id.''" class="btn primary Large">
';
}}
echo '
</div>';
include "../includes/footer.php";
?>
Execute Code:
<?php
include "../includes/dbconnect.php";
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$doc_id = intval($_POST['doc_id']);
$jat_id = intval($_POST['jat_id']);
$div_id = intval($_POST['div_id']);
$req = intval($_POST[$name]);
$req_blank = intval($_POST['req0']);
if ($req_blank == 0) {
$requirement = 0;
} elseif ($req_blank == 1) {
$requirement = 1;
} elseif ($req_blank == 2) {
$requirement = 2;
} elseif ($req == 0) {
$requirement = 0;
} elseif ($req == 1) {
$requirement = 1;
} elseif ($req == 2) {
$requirement = 2;
}
foreach ($doc_id as $doc_id2) {
$order = "INSERT INTO document_assoc (jat_id, dept_id, doc_id, requirement) VALUES ('$jat_id', '$div_id', '$doc_id2', '$requirement')";
$result = mysql_query($order);
$order1 = "SELECT * FROM divisions WHERE id = '$div_id'";
$result1 = mysql_query($order1);
while ($row1 = mysql_fetch_array($result1)) {
$dbname = $row1['division_dbname'];
$order2 = "SELECT * FROM $dbname WHERE id = '$jat_id'";
$result2 = mysql_query($order2);
while ($row2 = mysql_fetch_array($result2)) {
$type = $row2['type'];
$type2 = strtolower($type);
if($result){
header("location:view-$type2.php?id=$jat_id&creation=success");
} else {
header("location:view-$type2.php?id=$jat_id&creation=failed");
}
}}
}
?>
A few reference points:
$doc_id is the ID of each document which is to be passed over as an array for use in a (i believe) foreach insert
$jat_id is the ticket id documents are being associated to
$div_id is the department the ticket is associated
And the radio boxes are to decider the requirement of each document. To be passed over inline with $doc_id
What I have tried:
After a fair bit of searching - finding nothing - rechecking my terminology and searching again I managed to find the suggestion of using base64_encode(serialize()) on the arrays but I could not get this to work.

Liking system states that variable isn't defined, even though it is

I have the following code (below) to that loads the likes for a specific status (for dynamic use), it works if a user is liking their own post. But if a user is liking someone elses, it epically fails.
My code:
<?php
mysql_connect ('localhost', 'funding9_joeb', 'Brailsf0rdJ0e');
mysql_select_db ('mingle');
include('../includes/ts.php');
$_COOKIE['wds'];
$ssid = $_COOKIE['wds'];
$lu = "SELECT * FROM mingle_sessions WHERE sid = '$ssid' LIMIT 1";
$luq = mysql_query($lu) or die (mysql_query());
while($uidr = mysql_fetch_assoc($luq)) {
$uid = $uidr['uid'];
}
$sql = "SELECT * FROM users WHERE uid = '$uid' LIMIT 1";
$s = htmlentities(strip_tags(stripslashes($_GET['sid'])));
$result = mysql_query($sql) or print ("Can't select entry from table mingle_usr.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$fname = stripslashes($row['fname']);
$sname = stripslashes($row['sname']);
$dp = $row['dp'];
}
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$sql = "SELECT * FROM mingle_likes WHERE byuid = '$uid' AND onuid = '$s' AND type = 'status'";
$sr = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($sr) >= 1) {
$re = ("SELECT id as id, status as status, sid as sid, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_status WHERE uid = '$uid' AND sid = '$s' ORDER BY timestamp DESC LIMIT 1"); //query
$result = mysql_query($re) or die (mysql_error());
while($st = mysql_fetch_assoc($result)) {
$status = nl2br($st['status']);
$sid = $st['sid'];
$td = $st['timestamp'];
$id = $st['id'];
}
$like = mysql_fetch_array(mysql_query("SELECT COUNT(*) as num FROM mingle_likes WHERE onuid = '$sid' AND type = 'status' AND byuid != '$uid'"));
$likes = ceil($like['num']);
$haslike = mysql_fetch_array(mysql_query("SELECT COUNT(*) as nu FROM mingle_likes WHERE onuid = '$sid' AND type = 'status' AND byuid = '$uid'"));
$hasliked = ceil($haslike['nu']);
?>
<script type="text/javascript" src="js/ld_s.js"></script>
<form action='ld.php' method='post' id='ls' style='display:inline; border:0px; margin: 0 0 0 0; padding: 0 0 0 0;'>
<input type="hidden" class="do_<?php echo $sid; ?>" name="onuid" value="<?php echo $sid; ?>" />
<input type="hidden" class="db_<?php echo $sid; ?>" name="byuid" value="<?php echo $uid; ?>" />
<input type="hidden" class="dp_<?php echo $sid; ?>" name="uid" value="<?php echo $uid; ?>" />
<input type="hidden" class="dt_<?php echo $sid; ?>" name="type" value="status" />
<?php
if($hasliked == 1) {
?>
<label>You <?php if($likes >= 1) { echo "and " . $likes . " other people like this"; } else{ echo "liked this |"; }?></label><input type="submit" id="like" class="<?php echo $sid; ?>" name="submit" value="Unlike" />
<?php
}
else {
?>
<label><?php if($likes >= 1) { echo $likes . " people like this |"; }?></label><input type="submit" id="like" class="<?php echo $sid; ?>" name="submit" value="Like" />
<?php
}
?>
</form>
<?php echo time_since($td); ?>
<?php
}
?>
The errors are as follows:
( ! ) Notice: Undefined variable: sid in C:\wamp\www\mingle\ajax\loadslikes.php on line 47
and then the same again for every occurrence of $sid.
I haven't got a clue why at all, like I say, it works perfectly for the user liking his/her own post, just not others.
Any ideas? :-/

php session vars

I'm working on news archive page for my website, search over archive is done with start date, end date and news category as search parameters. Form values are stored in $_SESSION var, and then they are passed around as an array for pagination and other purposes.
My question would be how to prevent displaying search results on main archive search page if user for some reason goes again to it to make a new search.
here's the code
<?php
session_start();
if (isset($_POST['submit'])) {
//get data from the form
$archFld_1 = $_POST['archiveFld1'];
$archFld_2 = $_POST['archiveFld2'];
$archFld_3 = $_POST['archiveFld3'];
//just some check on fields
if (strlen($archFld_1) > 10) { $archFld_1 = ""; }
if (strlen($archFld_2) > 10) { $archFld_2 = ""; }
//save them as a array and store to session var
$_archValues = array($archFld_3, $archFld_1, $archFld_2);
$_SESSION['storeValues'] = $_archValues;
}
if (isset($_SESSION['storeValues'])) {
//check params for search
//set cat for query
if ($_SESSION['storeValues'][0] > 0) { $valCat = "AND newsCat=". $_SESSION['storeValues'][0] ." "; } else { $valCat = ""; }
//set date for query
if(($_SESSION['storeValues'][1] != "" ) && ($_SESSION['storeValues'][2] == "")) {
$DateStart = $_SESSION['storeValues'][1];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') >= STR_TO_DATE('$DateStart', '%d-%m-%Y') ";
}
if(($_SESSION['storeValues'][2] != "") && ($_SESSION['storeValues'][1]=="")) {
$DateEnd = $_SESSION['storeValues'][2];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') <= STR_TO_DATE('$DateEnd', '%d-%m-%Y') ";
}
if(($_SESSION['storeValues'][1]!="") && ($_SESSION['storeValues'][2] != "")) {
$DateStart = $_SESSION['storeValues'][1];
$DateEnd = $_SESSION['storeValues'][2];
$valDate = " AND STR_TO_DATE(newsDate, '%d-%m-%Y') BETWEEN STR_TO_DATE('$DateStart', '%d-%m-%Y') AND STR_TO_DATE('$DateEnd', '%d-%m-%Y') ";
}
//query string and stire it to session
$archQuery_string = $valCat.$valDate;
$_SESSION['storeQuery'] = $archQuery_string;
}
//pagination start
$page = $_GET['id'];
$perPage = 10;
$result = wbQuery("SELECT * FROM wb_news WHERE newsLang=1 ". $_SESSION["storeQuery"] ."ORDER BY newsId DESC");
$totalPages = mysql_num_rows($result);
if(!$page)
$page = 1;
$start = ($page - 1)*$perPage;
?>
<div id="sps_middle">
<div class="sps_cnt">
<div id="sps_middle_ly1">
<div class="sps_cnt_small">
<div class="sps_page_title"><h3><?php echo $wb_lng['txtArchiveTitle']; ?></h3></div>
<div class="sps_pages_cnt" style="padding-top: 10px; float: left; margin-bottom: 15px;">
<div class="sps_middle_col01">
<div style="float: left;">
<p>
<?php echo $wb_lng['txtArchiveInfo']; ?>
</p>
<form action="<?php $PHP_SELF; ?>" method="post" name="archiveForm" class="archiveForm">
<ul>
<li>
<input name="archiveFld1" type="text" id="archiveFld1" value="<?php echo $wb_lng['txtArhivaFld_01']; ?>" />
<input name="archiveFld2" type="text" id="archiveFld2" value="<?php echo $wb_lng['txtArhivaFld_02']; ?>" />
<select name="archiveFld3">
<option value="0"><?php echo $wb_lng['txtArhivaFld_07']; ?></option>
<option value="0" ><?php echo $wb_lng['txtArhivaFld_06']; ?></option>
<option value="1"><?php echo $wb_lng['txtArhivaFld_03']; ?></option>
<option value="2"><?php echo $wb_lng['txtArhivaFld_04']; ?></option>
<option value="3"><?php echo $wb_lng['txtArhivaFld_05']; ?></option>
</select>
</li>
<li style="float: right;">
<input name="reset" type="reset" class="sps_archiveform_btn" value="<?php echo $wb_lng['txtArchiveFormReset']; ?>"/>
<input name="submit" type="submit" class="sps_archiveform_btn" value="<?php echo $wb_lng['txtArchiveFormSend']; ?>"/>
</li>
</ul>
</form>
</div>
<hr />
<?php
if (#HERE GOES SOME CODE TO PERFORM THE CHECK!!!#) {
//perform db query
$result = wbQuery("SELECT * FROM wb_news WHERE newsLang=1 ". $_SESSION['storeQuery'] ."ORDER BY newsId DESC LIMIT $start, $perPage");
//count rows
$totalnews = mysql_num_rows($result);
$count = 1;
if($totalnews == 0) {
//no results, say to the user
echo "\t\t\t<div class=\"cil_news_text_big\">\n\t\t\t\t".$wb_lng['txtArchiveNoEntries']."\n\t\t\t</div>\n";
} else {
//we have results, yeeeeeeeeey
while($ROWnews = mysql_fetch_object($result)){
//set link extensions by the news cat
switch ($ROWnews->newsCat) {
case 1:
$newsCat_link = "news";
break;
case 2:
$newsCat_link = "statements";
break;
case 3:
$newsCat_link = "events";
break;
}
//text summary
if (strlen($ROWnews->newsShort) > 0 ) {$newsShortTxt = strip_tags($ROWnews->newsShort);
if ($lang_id==2) { $newsShortTxt = wbTranslit($newsShortTxt); }
} else {
$newsShortTxt = strip_tags($ROWnews->newsFull);
if ($lang_id==2) { $newsShortTxt = wbTranslit($newsShortTxt); }
}
$newsShortTxt = wbShorTxt($newsShortTxt, 210, "... <a title=\"".$wb_lng['txtShowMore']."\" href=\"http://".$_SERVER['HTTP_HOST']."/".$lang_link."/".$newsCat_link."/".$ROWnews->newsId."/full/\">".$wb_lng['txtShowMore']."...</a>");
//show news
echo "\t\t<div class=\"sps_news_list\">\n";
echo "\t\t<div class=\"sps_news_l\">\n";
echo "\t\t\t<img alt=\"\" src=\"http://".$_SERVER['HTTP_HOST']."/content/images/news/_thumb/".$ROWnews->newsImageThumb."\" />\n";
echo "\t\t</div>";
echo "\t\t<div class=\"sps_news_r\">\n";
//transliterate title
if ($lang_id==2) { $newsTitle = wbTranslit($ROWnews->newsTitle); } else { $newsTitle = $ROWnews->newsTitle; }
echo "\t\t\t<div class=\"sps_news_title\">\n\t\t\t\t<a title=\"".$newsTitle."\" href=\"http://".$_SERVER['HTTP_HOST']."/".$lang_link."/".$newsCat_link."/".$ROWnews->newsId."/full/\">".$newsTitle."</a>\n\t\t\t</div>\n";
echo "\t\t\t<div class=\"sps_news_date\">\n\t\t\t\t".$ROWnews->newsDate."\n\t\t\t</div>\n";
echo "\t\t\t<div class=\"sps_news_text_sh\">\n\t\t\t\t".$newsShortTxt."\n\t\t\t</div>\n";
echo "\t\t</div>";
echo "\t\t</div>";
//show <hr /> based on $count
if($totalnews != $count) { echo "\t\t\t<hr />\n"; }
$count++;
}
}
//pagination check
if($totalPages>$perPage) {
?>
<hr />
<div class="sps_pagginate">
<?PHP wbPageTurnFront($PHP_SELF."/".$lang_link."/archive/", $totalPages, $page, $perPage); ?>
</div>
<?php
}
}
?>
Any ideas?
Tnx :)
If user goes to make it a new search then you can clear the session at that time.
unset($_SESSION['storeValues']);

Categories