Database entry multiple records - php

I have a table of inactive users displayed in a table from a mysqli database. I have then created a new row for each user and a cell for each row containing a dropmenu with 3 options - admin , delete user, activate user.
$stmt = $mysqli->prepare("SELECT username, firstname, lastname, registerdate FROM users WHERE level < 1");
$stmt->bind_param('ssss', $_GET['username'], $_GET['firstname'], $_GET['lastname'], $_GET['registerdate']);
$stmt->execute();
$stmt->bind_result($username, $firstname, $lastname, $registerdate);
?>
<table>
<tr>
<th colspan="7"><h1>Inactive Users</h1></th>
<tr>
<td><h2>Username</h2></td>
<td><h2>Firstname</h2></td>
<td><h2>Lastname</h2></td>
<td><h2>Date Registered</h2></td>
<td><h2>Days Inactive</h2></td>
<td><h2>Activate</h2></td>
<td><h2>Submit</h2></td>
<?php
while ($stmt->fetch()){
$today = new DateTime("now");
$registered = new DateTime($registerdate);
$dayspassed = date_diff($registered, $today);
echo '<tr class="'.$username.'">
<td>'.$username.'</td>
<td>'.$firstname.'</td>
<td>'.$lastname.'</td>
<td>'.$registered->format("d-m-y").'</td>
<td>'.$dayspassed->format("%a days").'</td>
<td>
<select name="'.$username.'" id="'.$username.'">
<option selected>Select Action</option>
<option value="activate">Activate User</option>
<option value="delete">Delete User</option>
<option value="admin">Admin</option>
</select>
</td>
<td><input type="submit" name="'submit'" value="Confirm" />
</td>';
}
$stmt->close();
?>
</table>
I'm trying to write some basic code that will be something like foreach dropmenu with the value "activate" insert user into table activated. Each select menu has the name of $username collected from the db table. So far i have something like this.
if(isset($_POST['submit']))
{
$activate = $_POST["activate"];
$delete = $_POST["delete"];
$admin = $_POST["admin"];
foreach ($username == $_POST["activate"]{

First of all, when handle $var equals $_POST, you need to check if $_POST is set, otherwise you'll get an error.
if(isset($_POST['activate'])) $activate = $_POST['activate'];
ok, then, if you select 4 users for example, if you want to handle it, you can use Ajax. with js turn off the default action on submit button, then take all ids for activate, all ids for delete and all ids for anything that you want and concat on an array like array['action_type']['user_id'];
then, you just send it by $_POST to another php to handle.
For better example explanation, you can get:
array['activate']['1'];
array['activate']['2'];
array['delete']['3'];
array['activate']['4'];
Or you can get
array['activate']['1,2,4'];
array['delete']['3'];
then you can activate users 1, 2 and 3, and delete user 4 in a loop (use what you like. while, do-while, for, foreach...)
Hope it helps!

Php for select:
<select name="'.$username.'" onchange="updateUser(this)" id="'.$username.'">
Then javascript (with jQuery):
function updateUser(param) {
var username = $(param).attr('id');
var action = $(param).val();
var phpDataPrepare = [username, action];
var phpData = JSON.stringify(phpDataPrepare);
$.ajax({
url:'<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . "?action=update_user"; ?>',
data: phpData,
type: 'POST',
success: function(data){
//data = response
//put any javascript here as a success function if needed.
}
});
}
Then just write the PHP to receive this information (near the top of the same page)
To get your information:
if(isset($_GET['action']){
if($_GET['action'] == 'update_user'){
$info = json_decode(file_get_contents('php://input'));
$username = $info[0];
$action = $info[1];
//Do what needs to be done
exit();
}
}

Related

Use selected Option as variable in PHP Select Dropdown

I'm pulling data from an Azure SQL database using PHP and have successfully created a drop-down (Select) box with Options that are pulled from the database.
The SQL query returns 2 columns, Title & Cycle_ID.
I have set the Title as the text string and the Cycle_ID as the value.
I now want to store the value (Cycle_ID) of the current selection in a variable (MyVariable), which I will use in the SQL query for the next drop-down box I'm creating, i.e. WHERE Cycle_ID = MyVariable.
This way the user progressively narrows their selection as they work their way down through my drop-down boxes.
My current code is below, but I don't know how to create and store the current selection to MyVariable.
<?php
//create the database connection and define the query
$serverName = "myserver";
$connectionOptions = array(
"Database" => "mydatabase",
"Uid" => "mysqlaccount",
"PWD" => "mypassword"
);
//Establishes the connection
$conn = sqlsrv_connect($serverName, $connectionOptions);
//defines cycle query
$cyclesql= "SELECT [Cycle_ID]
,[Title]
FROM [ods].[Cycle]
WHERE End_Date > DATEADD(month,-6,GETDATE()) AND Updated IS NOT NULL
ORDER BY Cycle_ID Asc";
$cycleResults= sqlsrv_query($conn, $cyclesql);
if ($cycleResults == FALSE)
echo (sqlsrv_errors());
?>
<html>
<body>
<form action="cyclefile.php" method="post">
<div id="select">
<p>Select the week:</p><select name='Week'>
<option value="">Select...</option>
<?php
//starts loop
while ($row = sqlsrv_fetch_array($cycleResults, SQLSRV_FETCH_BOTH)) {
//defines cycle variable
$cycle = $row['Title'];
//defines cycle_id variable
$cycle_id = $row['Cycle_ID'];
//displays cycle variable as option in select (dropdown) list and cycle_id as value
echo '<option value="'.$cycle_id.'">'.$cycle.'</option>';
}
?>
</select>
</div>
</form>
</body>
</html>
I suggest you to make an ajax call on selection and pass the selected value to process your result in another file where you can run your query.
<select name="cycle_data" id="cycle_id">
<option value="cycle1" > Cycle 1</option>
<option value="cycle2" >Cycle 2</option>
</select>
Then lets do a script:
<script type="text/javascript">
$(document).ready(function(){
$("#cycle_id").change(function(){
var cycle_data = $(this).val();
var dataString = "cycle_data="+cycle_data;
$.ajax({
type: "POST",
url: "get-data.php",
data: dataString,
success: function(result){
// Process your result here
}
});
});
});
</script>

Autopopulate form fields with mysql values based on dropdown selection

I have a basic form that I would like to have other fields appear underneath such as email address and job title when the user is selected from the drop down.
The process will be:
User selects name from the drop down
PHP, JQUERY to query mysql database where user is equal to the selection from dropdown
Email address and Job Title fields to appear underneath with populated information.
My JQuery doesn't seem to work on my page...
I have used the code from this Stack Overflow question in which my reply was removed because it was not a 'solution': Populate input fields with values when option is selected - php mysql
Any help on this would be appreciated!
self_submit.html
<html>
<head>
<title>TEST</title>
<script>
$(document).ready(function(){
$('#user').on('change',function(){
var user = $(this).val();
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
async : false,
data : { user : user},
success : function(data) {
userData = json.parse(data);
$('#age').val(userData.age);
$('#email').val(userData.email);
}
});
});
});
</script>
</head>
<body>
<form>
User
<select name="user" id="user">
<option>-- Select User --</option>
<option value="username1">name1</option>
<option value="username1">name2</option>
<option value="username1">name3</option>
</select>
<p>
Age
<input type="text" name="jobtitle" id="jobtitle">
</p>
<p>
Email
<input type="text" name="email" id="email">
</p>
</form>
</body>
</html>
getUser.php
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_GET['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
json_encode($row);die;
?>
Thanks in advance
you need to change your ajax call to:
$.ajax({
url : "getUser.php",
dataType: 'json',
type: 'POST',
data : { user : user },
success : function(data) {
userData = json.parse(data);
// $('#age').val(userData.age);
$('#jobtitle').val(userData.jobtitle); // Since you are selecting jobtitle, not age
$('#email').val(userData.email);
}
});
And also you forgot to echo your data:
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$user = $_REQUEST['user'];
$sql = mysqli_query($link, "SELECT jobtitle, email FROM tblusers WHERE username = '".$user."' ");
$row = mysqli_fetch_array($sql);
echo json_encode($row);
exit();
?>
Hope this helps!
Define "POST" method in form tag
download jquery library for offline use or use google cdn or microsoft -then reference it in head html tag
change the data in ajax to data: "user="+user, am used to this format
lastly use proper id names correctly, incorrectly referencing 'ids', you reference in html email id =
$('#jobtitle').val(userData.age);
instead of
$('#email').val(userData.age)
this is fine =>
$('#email').val(userData.email);
$user = $_GET['user']; change to $user = $_POST['user'];
These are some mistake I observed without running you code if still you run into problems ask then

PHP & jQuery - Create two different textfields with autocomplete having different lists of data retrieved from the database

Customer textfield with autocomplete from database
I succeeded to create one Customer textfield with autocomplete to display customers which start by the text being typed.
index.php for one textfield
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#customer" ).autocomplete({
source: "../phpfiles/search.php",
});
});
</script>
<div class="ui-widget">
<!-- action='./../customer_report_request' -->
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
</table>
</form>
</div>
<?php
//Display the list of customer details
if(isset($_POST['send_customer_request']))
{
include 'db.php'; //connection
$query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'";
$customer_result = $db->query($query);
$count_customer = $customer_result->num_rows;
if($count_customer>0)
{
echo"<div>";
echo "<table>";
echo"<tr>";
echo"<th>Company_Name</th>";
echo"<th>VAT_Registration</th>";
echo"<th>Contact_First_Name</th>";
echo"<th>Contact_Last_Name</th>";
echo"<th>Email</th>";
echo"</tr>";
while ($row = $customer_result->fetch_assoc())
{
echo"<tr>";
echo"<td>".$row['Company_Name']."</td>";
echo"<td>".$row['VAT_Registration']."</td>";
echo"<td>".$row['Contact_First_Name']."</td>";
echo"<td>".$row['Contact_Last_Name']."</td>";
echo"<td>".$row['Email']."</td>";
echo"</tr>";
}
echo "</table>";
echo"</div>";
}
$db->close();
}
?>
Search.php for one textfield
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from customer table
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc()) {
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
?>
The problem is I want to use a single search php file to cater for other queries.
For example:
If a word is typed in the Contact textfield, the query will be
"SELECT * FROM Contact...."
If a word is typed in the Customer textfield, the query will be
"SELECT * FROM Customer...."
Both index.php and search.php were modified to achieve this.
Modified part in index.php
A jQuery variable, component_name was defined. On change from the index.php file, the customer texfield will send the variable to search.php file using a POST method so that it can be identified and used for query purposes.
The contact textfield can be either in the same form in the index.php file or in another php file.
<script>
$(function() {
$( "#customer" ).autocomplete({
var component_name= "customer";
source: "../phpfiles/search.php",
minLength: 1,
change: function(event, ui)
{
$.post("../phpfiles/search.php", data{post_data: component_name});
}
});
});
</script>
Modified search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query="";
if($_POST['post_data']=="customer")
{
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc())
{
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
}
?>
Can anyone help me to achieve this?
I used these links for the jquery-ui and jquery api parts:
api.jquery.com
jqueryui.com
This may be a little complicated ad I hope it helps. Your example does not provide any example data or schema to your DB, so I had to make a number of guesses. You'll need to adjust.
Consider if you have different input fields, you could have:
HTML
<div class="ui-widget">
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input class="entry-field" name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
<tr>
<td>
<label>Contact: </label>
<input class="entry-field" name="contact" id="contact" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request">
</td>
</tr>
</table>
</form>
</div>
JavaScript
$(function() {
$(".entry-field").autocomplete({
source: function(req, resp) {
// determine which field we're working with
var type = $("this").attr("id");
// collect the entry in the field
var term = req.term;
// Prepare our response array
var responses = [];
// PErform POST Request to our Search and accept JSON results
$.ajax({
url: "../phpfiles/search.php",
data: {
t: type,
q: term
},
type: "POST",
dataType: "JSON",
success: function(results) {
$.each(results, function(key, val) {
responses.push(val);
});
}); resp(responses);
},
minLength: 1
}
});
$("#customer_report_request").submit(function(e) {
e.preventDefault();
if ($("#customer").val().length) {
// perform POST to a PHP search for that specific customer details
} else {
// performn a post to a PHP search for that specific contact details
}
// populate result DIV on page with resulting data from POST
});
});
PHP: search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
// get search query
$searchTerm = $_POST['q'];
// get search type
$searchType = $_POST['t'];
//get matched data from customer table
if($searchType == "customer"){
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'");
} else {
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'");
}
/* bind parameters for markers */
$stmt->bind_param("s", $searchTerm);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
if($searchType == "company"){
$data[] = $row['Company_Name'];
} else {
$data[] = $row['Contact_Name']
}
}
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
So there is a lot going on. Will start with your PHP. It was vulnerable to SQL Injection, so I made use of MySQLi Prepare to protect things. We are expecting data to be posted to this script, and we're expecting to conditions: query and type. If we do not get a type, we can set defaults. Might want to add a check for query, but it should always have 1 character.
We get this data to our Search script using the function method for the source option. See more: http://api.jqueryui.com/autocomplete/#option-source
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
So with this, we can add to our $.ajax() call and make use of the error callback. Basically, we've end up sending an empty array back to response.
So we send a send a search term to PHP, we get JSON array data back, we pipe this into our own array to send back to response, and the user will get a list of results.
It's still a little clunky and that's ok if that's what you're users are used to. You can slim it down and also categorize your results. This way you can have one search field. Also once something is selected or the field is change, you can then use AJAX again to pull those details from another PHP that harvests all the data from the DB. This would result in not having to wait for the page to load again etc.
I hope this answer your question and I suspect it will raise more too. Keep searching around, there are lots of answers. Sometimes it's easier to break a big problem down into smaller single questions than to tackle the whole.

Integrating href with $_GET value into a select option

I am trying to get some data of a certain item selected in a select option and automatically display it on the textfield as shown in this image:
But it is not working. Is there a remedy for this or such type of coding is not workable at all? Hopefully someone can help me on this.
Here is the code I made:
$credit_accounts = $db->query("SELECT * FROM credits");
echo'<select id="customer_order_id" name = "customer_order_id">
<option value = "">SELECT ACCOUNT</option>';
foreach($credit_accounts as $key){
$id = $key['purchase_order_id'];
$name = $key['customer_firstName']."\t\t".$key['customer_lastName'];
echo'<option value = "'.$id.'">'.$name.'</option>';
}
echo'
</select>';
Note: The link will execute a query that will retrieve certain data of the selected item. If link is declared outside the loop without the <option></option> tag, it works accordingly. But if it is place within the loop of course with the <option></option> tag, it is not working like a link at all. Please help me out.
Sorry for my english , I will write some long answer hopefully it will also help others,so i am giving solution for doing following.
Please not : this solution is written and use SIMPLE MYSQL,AJAX and PHP function If you further want DATA SECURITY refer [PHP MySQLI Prevent SQL Injection
Objective : To get/display DATA from DATABASE related to a particular(ly 1) user/product and then fetch/display it in HTML page (additionally: without page refresh ) IN A FORM.
CODE :
<?php
//php-database connection script
$db_config = mysqli_connect("localhost", "username", "pass", "database_name");
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
?>
<?php
//this pHP SCRIP FIRES when you select a USERNAME (if u want not to SELECT but type then change ONCHANGE to ONKEYUP function & change username input type to text)
if(isset($_POST['uname'])){
$u = $_POST['uname'];
$sql = "SELECT email , gender FROM credits WHERE username='$u' LIMIT 1";
$query= mysqli_query($db_config,$sql);
while($row2 = mysqli_fetch_array($query)){
//Here we form a STRING SEPRATED BY QUAMMAS and ECHO IT TO PAGE
//later on we will fill this data in input fields
echo $row2['email'].",".$row2['gender'];
exit();
}exit();}
?>
<!-- HERE is your form where user will select or type his username-->
<form >
Select username :<br/>
<select id="user_name" onchange="load_data()">
<option value=""> select an ouser</option>
<option value="v1111"> v111</option>
</select><br/>
Email<br/>
<input type ="text" id="email" value=""><br/>
Gender :
<select id="gender">
<option value='m'>male</option>
<option value='f'>female</option>
</select>
</form>
<span id='status' ></span>
<script>
//AJAX OBJECT CREATION script it works as get or post mechanism
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
//here is function which fires when username is selected
function load_data(){
var value = document.getElementById('user_name').value;
//declare ajax obj, and name(url) of same page you are coding.
var ajax = ajaxObj("POST", "url.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var str = ajax.responseText;
//split STRING and extract individual data
var res = str.split(',');
//here we fetch his username into input field BINGO!do same for gender.
_('email').value = res[0];
//res[1] will have gender related data.
}
}
//Declaration to send URL encoded variable (username in this case)
ajax.send("uname="+value);
}
</script>
If you want further resources and info about data security see BRAD's comments in comments section

Pre Populating a PHP Dynamic Select Option with Stored Session Variable

Im scratching my head once again and need your help.
What I have is a form that submits to a second page, with sessions enabled, i am storing the name value 2 fields on the form and setting their value names in the session so that if a user returns to a page their Username will already be populated in the text field. I have this working ok ..
The second page i am storing
$_SESSION['captured_by'] = $_POST['captured_by'];
$_SESSION['prid'] = $_POST['prid'];
HOWEVER..
Where i am stuck is getting a select option that is populated from a query to have the same functionality, so that when a user returns to the page, the selected option which has been saved in the session will keep that selection in the box rather than having to select it again.
Here is what i have as follows:
Form Page:
This does work and does return the captured_by text when i return to the page
<fieldset><legend>Lesson Added By *</legend>
<p class="multiple">(Required - Logon ID)</p>
<input name="captured_by" maxlength="12" id="searchfield" type="text" value="<?php
if(isset($_SESSION['captured_by'])){print stripslashes($_SESSION['captured_by']);}
else{print " ";} ?>">
</fieldset>
The problem code is this
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'">'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
I need to edit this last section so that it picks up the previously selected option value from the stored session value.
Hope someone can help?
Many Thanks.
Tazzy
Try this,
<select id="searchfield" name="prid">
<?php
$query = "SELECT project_name, project_id FROM ll_project ORDER BY project_name ASC;";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['project_id'].'"'. ((isset($_SESSION['prid']) && !empty($_SESSION['prid']) && ($_SESSION['prid'] == $row['project_id'])) ? 'selected="selected"' : '') .'>'.$row['project_name'].' | '.$row['project_id'].'</option>';
}
?>
</select>
</fieldset>
You could simply use ajax when someone change the selection.
$('select#searchfield').change(function(){
$.ajax({
type: 'GET',
url: 'changeSession.php', // This is the url that will be requested
data: {prid: $('select#searchfield').val()},
success: function(html){
// nothing really happens because you simply update your session
},
dataType: 'html'
});
});
Then in changeSession.php
if(isset($_GET['projectId']{
$_SESSION['captured_by'] = $_POST['prid'];
}
That should do the job. You then add a condition when the form is generated and you add selected='selected' if $_SESSION['prid'] is not empty.

Categories