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
Related
In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().
I'm new at php. I get the last id from database. For each id I want the state and the link. I'll check if state == 1, then get the content of the link (there's JavaScript variable that I need that is in the content of link). I'll send that variable with location.href.
Then I get that variable with $_GET in the second page. I want to store that var into database, then come back to first page and get the second link from the database and again do the same works.
How can I send the $j into second page for saving the x_cor and y_cor, and how to increase the $j when it comes to first page again?
<html>
<head>
<title>firstpage</title>
</head>
<body>
<?php
include_once ('simple_html_dom.php');
include_once ('split_unicode_function.php');
// getting the last id from db
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$sql = "SELECT id FROM netbarg ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $connection);
$rows = mysql_fetch_array($result);
$last_id = $rows['id'];
// getting id and link for each column
for ($j = 1; $j <= 2; $j++)
{
$select_db = mysql_select_db("kk", $connection);
$id = "SELECT state FROM `table` WHERE id='$j' ";
$result = mysql_query($id, $connection);
$row = mysql_fetch_array($result);
echo $state = $row[0] . '<br />';
// getting link
$link = "SELECT link FROM `table` WHERE id='$j' ";
$result = mysql_query($link, $connection);
$rows = mysql_fetch_array($result);
$link = $rows[0];
// (state is just 1 or 2)check if the state is 2 or not...
if ($state == 1)
{
$f = file_get_contents($link);
echo "<div>$f</div>";
}
}
?>
<script>
$("body").hide();
location.href ='secondpage.php?val='+point0+;
</script>
</body>
</html>
second page
<html>
<head>
<title>second page</title>
</head>
<body>
<?php
if (isset($_GET['val']))
{
$hat = $_GET['val'];
echo $hat;
$coords = trim($hat, '()');
// echo $coords.'<br />';
$a = array();
$a = explode(",", $coords);
var_dump($a);
echo $long = $a[0];
echo '<br />';
if ($long == "undefined") $lat = "undefined";
else echo $lat = $a[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$update = "UPDATE `table` SET `x_cor`='$long',`y_cor`='$lat' , `state`='2' WHERE `id`='$j' ";
$insert_todb = mysql_query($update, $connection);
if ($insert_todb) echo "coordinates has been updated", '<br />';
}
}
?>
<script>
location.href ='firstpage.php';
</script>
</body>
</html>
if get the last insert id use mysqli_insert_id($con);
it return last insert id from database using this geted id you can
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
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
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.