PHP echo selected value from html dropdown list - javascript

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().

Related

How to show alert box after successful or not data deletion in mssql

I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.
echo "<a class='activater' href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'> <span class='glyphicon glyphicon-trash'></span></a>";
It calls the following php Page, which handle the SQL Part:
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($sth)
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
echo sqlsrv_errors();
header("location: ma_QualiOverview.php?message=failed");
}
$connection = null;
Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.
<?php
if($_GET['message']=='success'){
echo '<script language="javascript">';
echo 'alert("Erfolgreich gelöscht.");';
echo '</script>';
} elseif($_GET['message']=='failed'){
echo '<script language="javascript">';
echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
echo '</script>';
}
?>
What do i miss?
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.
Since $sth is always defined, you always get the success result
See the modified code here
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($result )
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
header("location: ma_QualiOverview.php?message=failed");
echo sqlsrv_errors();//Echo must be after header
}
$connection = null;

How to display the body of the mail in another page if clicked on the subject

So I am creating an inbox in PHP and It displays Mail Id and Subject.
If you click that division(containing mail id and subject), it opens up a new page, read. PHP where the body and attachments are displayed.
I am facing some problem in getting to know which division is being clicked and how to display the mail of that particular person.
My concerned code is:
<?php
$conn = connect(); //Connects to the database
$sql = "select senderId, subject, body, attachment from mail where receiverId = '".$_SESSION["Email"]."' ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='mail' onclick='location.href=`read.php`;'>";
echo $row["senderId"] . " - " . $row["subject"];
echo "</div>";
echo "<hr />";
}
$conn->close();
?>
I have an idea of storing the variables using SESSION as:
if (isset($_GET['div'])) {
$_SESSION["body"] = $row["body"];
$_SESSION["attachment"] = $row["attachment"];
}
But where do I place the latter part of the code and suggest me if I can make an modifications please.
You can echo out the id during the while loop iteration.
echo "<div class='mail' onclick='location.href=`read.php?id=". $row['id'] ."`;'>";
And inside the read.php file, you can then grab that value by using $_GET['id'].

Select list ignores first value when using the onchange function, PHP, JAVASCRIPT

I'm using a select list function below to make a select list that have 5 values inside of it. Values 2-5 works fine when I select them, and they print out their values on the page when I select them, but value 1 does not print out no matter what. I cannot figure out what I did wrong or how to fix it. Please take a look at my code:
index.php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"index.php")
$value = $_POST['value'];
echo $value;
Add one first option to the < select >, and, check if $_POST['value'] exists. Next is your code with both changes pointed by commented arrows (//<=====) :
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>" .
"<option>Select an option</option>"; // <===========================
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>
The option "Select an option" will let the user to choose option 1.
If you don't want to see "Select an option", the other solution is to make the chosen option selected, for example, if the user chooses "3", when the page reloads the option "3" will be selected, and the user will be able to choose option "1" :
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
// MAKE THE CURRENT OPTION SELECTED IF IT WAS CHOSEN BEFORE. <==========
if ( isSet( $_POST['value'] ) && // IF 'value' EXISTS, AND
( $_POST['value'] == $tempCount ) ) // IF 'value' == CURRENT NUMBER
$selected = "selected";
else $selected = "";
echo "<option $selected value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>

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

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