Marking memos as read - javascript

I am putting together a site that handles H&S memos, and I need members to confirm that they have read their memos. I have looked at ways of handling this and they are based on assuming that members have read the memos the last time they logged on. I can't use this method as I need to assure their company that their workers have read their safety memos.
I have tried various ways of doing this but none are working well enough.
The main problem is selecting the correct ID number for the memo that they have clicked that they have read and then updating the details to the memo_read table. Any pointers, workarounds or solutions much appreciated.
This is what I have so far:
<?php
$user_id = $user_data['user_id'] ;
$company_id = $user_data['company'];
$nothing = '';
$result1 = mysql_query ("SELECT `user`, `memo_id` FROM`memo_read` WHERE `user`= '$user_id '") or die(mysql_error());
$memo_id_query = '';
while($row = mysql_fetch_array($result1)){
$memo_id_query .= " AND `id`!= '".$row['memo_id']."'";
}
?>
<div id="memo">
<h7>These are your unread memos!</h7>
<table class="bit">
<thead><tr><th>Title</th><th>Author</th><th>Time/Date</th><th>Memo</th></tr></thead>
<?php
$result = mysql_query ("SELECT `id`, `memos`, `author`, `time`, `title` FROM `memo` WHERE `worker`= 1 AND `company`='$company_id' ".$memo_id_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$memo = $row['memos'];
$author = $row['author'];
$time = $row['time'];
$title = $row['title'];
global $id;
?>
<tbody><tr><td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $time;?></td>
<td id="mem"><a class="toggle" href="#.bit" >read/hide</a>
<div class="hiddenDiv" ><?php echo $memo; ?><br>
<form id="tickmemo" action="" method="post">
<input type="submit" name="submit" value="mark as read">
</form>
</div></td></tr><tbody>
<?php
}
if (empty($_POST['submit']) === false) {
$q=("INSERT INTO `memo_read` VALUES ('$nothing', '$user_id', '$id') ");
$result = mysql_query($q) or die(mysql_error());
}
?></table></div>
(edit)
This is working great now i'll put it up here if anyone else needs it or if you can suggest any tweeks!
<?php
$user_id = $user_data['user_id'] ;
$company_id = $user_data['company'];
$nothing = '';
$result1 = mysql_query ("SELECT `user`, `memo_id` FROM`memo_read` WHERE `user`= '$user_id '") or die(mysql_error());
$memo_id_query = '';
while($row = mysql_fetch_array($result1)){
$memo_id_query .= " AND `id`!= '".$row['memo_id']."'";
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'You have marked that memo as read!<br>We will send you back in 3 seconds!';
header("Refresh: 3; url=\"http://www.testbed1.tk/login/index.php\"");
} else {
?>
<div id="memo">
<h7>These are your unread memos!</h7>
<table class="bit">
<thead><tr><th>Title</th><th>Author</th><th>Time/Date</th><th>Memo</th></tr></thead>
<?php
$result = mysql_query ("SELECT `id`, `memos`, `author`, `time`, `title` FROM `memo` WHERE `worker`= 1 AND `company`= '$company_id' ".$memo_id_query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$memo = $row['memos'];
$author = $row['author'];
$time = $row['time'];
$title = $row['title'];
?>
<tbody><tr><td><?php echo $title; ?></td>
<td><?php echo $author; ?></td>
<td><?php echo $time;?></td>
<td id="mem"><a class="toggle" href="#.bit" >read/hide</a>
<div class="hiddenDiv" ><?php echo $memo; ?><br>
<form id="tickmemo" action="#" method="post">
<input type="hidden" name="id" value="<?php echo $id;?>" />
<input type="submit" name="submit" value="mark as read">
</form>
</div></td></tr><tbody>
<?php
}
$id = $_POST['id'];
if (empty($_POST['id']) === false) {
$q=("INSERT INTO `memo_read` VALUES (''".mysql_real_escape_string($nothing)."'','".mysql_real_escape_string($user_id)."','".mysql_real_escape_string($id)."') ");
$result = mysql_query($q) or die(mysql_error());
header('Location: worker.php?success');
}
?></table></div>
<?php } ?>

There is a wide range of aspects here to comment on:
You have no input field "id" in your form, hence someone submitting the form cannot communicate what id they want to mark as read
You are assuming that register globals is on for the variable $id to be filled with a value. Instead use $_POST['id']
Your database queries lend themselves to SQL injection attacks, as you don't check any input. Use at least intval($_POST['id']) when saving to the database
mysql_query will be turned off in PHP5.5 I think, move to PDO
There is nothing wrong with doing it all in one file, but good programming style is to put the action logic at the top, output at the bottom.
If you need to scale the "read" table to a couple of 100000 rows, use this
I think the business case is flawed as well. It will probably lead to people clicking memos as read, in the best case have them actually read, but not understood and memorized. It may be better to create a peer-to-peer quiz system to memorize the memos.

Your application flow it's not really clear. You should have:
A page where you list the unread memo to the user. Every list item should have a link that points to memo description page.
Memo description page - in this page you actually insert in memo_read table the user_id and memo_id which has been read.

Related

Im trying to populate a dropdowm menu with a database column in php

I am trying to make a dropdown menu from a database. I am returning nothing right now. For the menu, I need to choose a object then run a SQL query on it. This query will populate a table and will be dynamic.
Here is the code, please help.
<html>
<?php
include('header.php');
?>
<h1>Chemicals Search</h1>
<br/ >
<br/ >
</head>
<h1>
<center>Chemical Search</center>
</h1>
<form action="chemicals.php" method="post">
<label>Search By Product:</label>
<?php
//making the chemical array
$con = mysqli_connect("...");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$p = mysqli_query($con, "SELECT product_name FROM product");
$products = mysqli_fetch_array($p);
echo '<select name="product">';
foreach ($product as $key => $value) {
echo "<option value=\"$key\"> $value</option>\n";
}
echo '</select>';
echo "<br>";
?>
</form>
Your Query only selects product name make a little changes to it
$p = mysqli_query($con,"SELECT product_id,product_name FROM product");
echo'<select name="product">';
if(mysqli_num_rows($p) > 0)
{
while($products =mysqli_fetch_array($p))
{
echo"<option value='".$products['product_id']."'>".$products['product_name']."</option>\n";
}
}
echo '</select>';
echo"<br>";
I am sure this will works, works for me everytime

Get mysql column of a clicked item

I have searched endlessly for an answer but have found none. I am trying to get the id of a clicked item. The item that I am clicking is from mysql database and has been displayed through a for loop. When the item is clicked I am taken to another page. In this page I want to utilize the id from the clicked item to get other information from that row in mysql database; this much I can do. The problem is getting the id from the clicked item and sending it.
This is the most recent way that I tried:
First I displayed the items from mysql.
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
$code = "<div id=\"challenge_preview\"><h7 class=\"challenge_preview_item\"
id=\"challenge_preview_name\"></h7><a href=\"challengeprofile.php\">
<video
class=\"challenge_preview_item\" id=\"challenge_video\"
src=\"".mysql_result($result, $i)."\"></video></a></div>";
echo $code;
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
Than I put the id in a hidden form so that I could attempt to POST it to the other page:
<form action="<?php echo $current_file; ?>" method="POST">
<input type="hidden" name="id" value="14">
</form>
On the script.php file that is included in both pages, I put
$(#challenge_video).click(function(){ <?php $id = $_POST['id']; ?> ;});
And on the page that the id is being posted to I put
<?php
include 'script.php';
echo getChallengeData('name', 'id', $id)
?>
Please help, Thank you
These are the edits
<div id='challenge_previews'>
<?php
$query = "SELECT `video` FROM `challenge_name` ORDER BY `id`";
$result = mysql_query($query);
if($result = mysql_query($query))
{
for($i = 0; $i < mysql_num_rows($result); $i++)
{
$id = $i;
echo "<div id=\"challenge_preview\"><video class=\"challenge_preview_item challenge_video\" src=\"".mysql_result($result, $i)."\"></video></div>";
}
}
else
{
die('Couldn\'t connect'. mysql_error());
}
?>
<form action="<?php echo $current_file; ?>" method="GET">
<input type="hidden" name="id" value="14">
</form>
</div>
This is the code for page 2
<h1 id="challenge_profile_name">
<?php
$id = substr(base64_decode($_GET['id']),6);
echo getChallengeData('name', 'id', $id);
?>
</h1>
This is the code for the getChallengeData method in the core.inc.php
function getChallengeData($field1, $field2, $field3)
{
$query = "SELECT `$field1` FROM `challenge_name` WHERE `$field2` = '$field3'";
if($query_run = mysql_query($query))
{
if($query_result = mysql_result($query_run, 0, $field1))
{
return $query_result;
}
}
}
That error that I'm getting has to do with the implementation of the getChallengeData method on page 2. The error says
Warning: mysql_result(): Unable to jump to row 0 on MySQL result index 10 in C:\xampp\htdocs\ChallengeNetworkWebsite\core.inc.php on line 42

Create session variables out of looped database values

I am attempting to create a variable from a database array when an HTML link is clicked. The goal is to redirect the user to a form populated using one piece of array data. In other words, the database will be queried and form populated according to which link is clicked (whatever the values of $row[1], $row[2], and $row[3] are).
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
If anyone can provide me with some incite as to how I could accomplish this I'd appreciate it greatly.
Please read more about sessions here
Then, to answer your question:
First you need to start the session, as simple as session_start(); on the top of your script.
Second you need to instantiate session variables with the DB values like this: $_SESSION['var'] = $value;.
Third, in the html file or whatever, where the form relies, just check for it:
if(isset($_SESSION['var'])) {
echo '<input type="text" value="'.$_SESSION['var'].'" />';
} else {
echo '<input type="text" value="" />';
}
and use the value if it is set.
L.E:
So... first thing's first... session_start(); without it, there is no point of having session.
Second, you create it like $_SESSION['some_name'] = $row[1] so that var will keep the value from $row[1]. I am presuming that it's the value you need. Do NOT do do it like $_SESSION['$row1'] because first of all this is incorrect, you will NOT have the value of row1 there. You need an unique name so that you can call it where you have the form.
The above code will become something like this:
<?php
session_start();
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$_SESSION['first_row'] = $row[1];
$_SESSION['second_row'] = $row[2];
$_SESSION['third_row'] = $row[3];
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
and, where you have the form and the <input type = "text" value = "" /> so where you need the value, just do it like this:
<input type = "text" value = "<?php echo (isset($_SESSION['first_row']) ? $_SESSION['first_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['second_row']) ? $_SESSION['second_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['third_row']) ? $_SESSION['third_row'] : ''); ?>" />
Hope this helps! :D

Retrieve data from database and display in textbox

How am i going to display the data from the database into the textbox? pls help
//Javascript textbox
<div class="Text">
<input class="Text" type="text" value="
<?PHP echo $id?>" name="id" size="19"/>
//PHP MYSQL Connect code
<?php
error_reporting(0);
include('../connection.php');
$id =$_REQUEST['id'];
$result = mysql_query("SELECT * FROM cust WHERE id = '$id'");
$test = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$id=$test['id'] ;
?>
Place your PHP code before HTML
//PHP MYSQL Connect code
<?php
error_reporting(0);
include('../connection.php');
$id =$_REQUEST['id'];
$result = mysql_query("SELECT * FROM cust WHERE id = '$id'");
$test = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$id=$test['id'] ;
?>
//Javascript textbox
<div class="Text">
<input class="Text" type="text" value="
<?PHP echo $id?>" name="id" size="19"/>
Note: mysql_* functions are deprecated. please try to use mysqli_* or PDO.
Put following PHP code before your HTML,
PHP
<?php
$con = new mysqli_connect(host,user,pass,dbname);
$id = $_REQUEST['id'];
$query = "SELECT * FROM cust WHERE id = '$id'";
$result = mysqli_query($query);
if (!$result)
{
die("Error: Data not found..");
}
$test = mysqli_fetch_array($result);
$id=$test['id'] ;
?>
HTML & PHP (inside body)
<div class="Text">
<input class="Text" type="text" value="<?PHP echo $id; ?>" name="id" size="19"/>
Hope this help you!
One good approach for element rendering is to make HTML Helper Libraries. Like for example create a class HTML having a set of static tag creator methods.
#Pseudo HTML helper class - HTML.class.php
class HTML
public static input(type, id, class, data, text)
public static heading(mode, text)
#Pseudo input tag helper - HTML.class.php::input
function input(type, id, value) {
# method create the html string for the given input.
return ["<input type=",type," id=",id," value=",value,"/>"].join('');
}
<?php
$con = new mysqli(host,user,pass,dbname);
$query = "SELECT * FROM cust WHERE id = '$id'";
$result = $con-> query($query);
while ($row = $result->fetch_assoc()){
$value = $row['id'];
echo HTML::input('text', id, $id);
}
?>
I think this just the same as above answers. but i prefer when you write code it should be modular, clean and beautiful. Always use good practices. Thats why i shared my thought here. If you create your own or others helper class help you with faster development also i suggest contributions to it help you in learning. I know that this is not the answer what you are looking, but anyway free to revert back at any time.
Working Solution
<?php
include("database.php");
$db=$conn;
// fetch query
function fetch_data(){
global $db;
$query="SELECT * FROM users WHERE username='vii'"; // change this
$exec=mysqli_query($db, $query);
if(mysqli_num_rows($exec)>0){
$row= mysqli_fetch_all($exec, MYSQLI_ASSOC);
return $row;
}else{
return $row=[];
}
}
$fetchData= fetch_data();
show_data($fetchData);
foreach($fetchData as $data){
$firstname=$data['udid'];} // change this 'udid' to your table field
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Retrieve Contact</title>
</head>
<body>
<input type=text value= <?php echo $firstname; ?>
</body>
</html>

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources