Require multiple rows from database using multiple select in php - php

I have a database witch contain users information and (with user name from database) and I have to show all information from database for user name selected.
<select name="user[]" id="user" multiple="multiple" tabindex="1" onchange="showUser(this.value)">
<?php while($row = mysqli_fetch_array($result)){
?>
<?php
foreach($result as $row){
?>
<option value ="<?php echo $row['username']; ?>"> <?php echo $row['username'];?></option>
<?php }
?>
<?php }?>
</select>
I can only display data for one user even if I select two or more
edit :
this is my script function and display function:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","123.php?q="+str,true);
xmlhttp.send();
}
}
</script>
123.php :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$q = $_REQUEST["q"];
require 'conectare.php';
mysqli_select_db($conectare,"users");
$sql = "Select * from users where username = '{$q}'";
$result = mysqli_query($conectare, $sql);
echo "<table>
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
<th>email</th>
<th>Telefon</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['telefon'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conectare);
?>
</body>
</html>
enter image description here
It looks like this, I want to display 2 or more users and it only shows me one

Here's I am trying to show how you can achieve it. To display tabular data without.
I am not answering the exact solution, because i want you learn the basics. this code
is for example only.
$connection = mysql_connect('localhost', 'root', '');
//The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
//Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
//$row['index'] the index here is a field name
}
echo "</table>";
//Close the table in HTML
mysql_close();
//Make sure to close out the database connection

You can open your browser tools, go to network and send the request, select the XHR pill and observe your request in the preview/response tab of the request. Also a good practice is to use parameterized queries. This web page is actually asking for someone to perform an SQL Injection.
The preview of your actual data will be really helpful in loading the page data to see what is the error that you are getting.

Related

how to add foreach array in text input

I have a form in which I enter the name, surname and function (result one select), I display them with a foreach in a table.
I want to add a button to every foreach record that will load the first form with the data from the row but I can not.
Thanks for the help!
<?php
require_once 'functii/functii.php';
$r = functia();
$options = "";
while ($row = mysqli_fetch_array($r)) {
$options = $options . "<option>$row[0]</option>";
}
?>
<form method="POST">
<table id="add"><tr><td>Nume:</td><td><input type="text" name="nume"/></td></tr>
<tr><td>Prenume:</td><td><input type="text" name="prenume"/></td></tr>
<tr><td>Functia:</td><td><select name="functia"><?php echo $options; ?></select></td></tr>
<tr><td>Activ:</td><td><input type="radio" name="activ"/></td></tr>
<tr><td></td><td><input type="submit" name="adaugare" value="Adauga"/><input type="submit" name="modificare" value="Modifica"/></td></tr></table>
</form>
<?php
if (isset($_POST['adaugare'])) {
require_once 'functii/functii.php';
$n = $_POST['nume'];
$p = $_POST['prenume'];
$f = $_POST['functia'];
$r = adaug_utilizator($n, $p, $f);
}
require_once 'functii/functii.php';
$utilizatori = grid_utilizatori();
if (count($utilizatori) == 0) {
print 'Nu sunt utilizatori adaugati';
} else {
?>
<table id="view">
<thead><tr><th colspan="4">Utilizatori adaugati</th></tr>
<tr><th>Nume</th><th>Prenume</th><th>Functia</th></tr>
</thead>
<tbody>
<?php
foreach ($utilizatori as $utilizator) {
print "<tr>";
print "<td>" . $utilizator['nume'] . "</td>";
print "<td>" . $utilizator['prenume'] . "</td>";
print "<td>" . $utilizator['denumire'] . "</td>";
print "<td><input type='submit' name='modifica' value='Modifica'></td>";
print "</tr>";
}
if (isset($_POST['modifica'])) {
$_POST['nume'] = $utilizator['nume'];
$_POST['prenume'] = $utilizator['prenume'];
$_POST['functia'] = $utilizator['denumire'];
}
?>
</tbody>
</table>
<?php
}
?>
You can execute loop as follows:
<?php
foreach($utilizatori as $index => $utilizator){
?>
<input type='submit' name='modifica<?php echo ($index+1);?>' value='Modifica' class="clickBtn"></td>
<?php
}
?>
with above loop name attribute will be as modifica1, modifica2 etc.
Now, you want to fill information based on button clicked to the form shown at your top of code, I think so.
For this, you can use jQuery:
$('.clickBtn').click(function(e){
var buttonOfRowClicked = $(this).attr('name');
var rowNumber = buttonOfRowClicked.substr(8); // It will get 1,2,3 etc table row.
$('input[name=nume]').val($(tr:nth-child(rowNumber) td:nth-child(1).val());
$('input[name=prenume]').val($(tr:nth-child(rowNumber) td:nth-child(2).val()); //similarly fill other variables.
});
I have not check the code by executing. It is overview for you to run your code. I think idea is sufficient for you for direction how should your code works.

Create a table from and SQL database containing a drop down menu with a list of names from another SQL table

I need to create a table with a drop down menu and submit button in each row.
The drop down menu contains a list of advisers from an SQL table. When i select and adviser and i press the submit button the id of the item in the current row along with then selected adviser id or name must be sent to another page. In my case it is sent to delete.php.
My code bellow displays a drop down menu and a submit button for each row of the table, however when you press the submit button it will only work correctly if you press the submit button located at the bottom of the table, if i press any other it appears to not send the info from the drop down menu.
( i know my code appear messy, i am experimenting if something is unclear ask me and i will clarify. )
Thank you very much!
<!DOCTYPE html>
<html>
<body>
<?php
//this is he code for the qeue
// connect to the database udinh sqli
$con = get_sqli();
// get results from database
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//select whole list of students from walk_in
mysqli_select_db($con,"login");
$sql="SELECT * FROM walk_in";
$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
mysqli_close($con);
//Table to dispaly qeueu of students
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last Name</th><th>Advisor Student wants to see</th><th>P ID</th><th>Select Advisor to notify on send</th><th>Send Student</th><th> </tr>";
echo "<tr>";
//create a table of students by displaying all the data from result and adding a button
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Advisor'] . "</td>";
echo "<td>" . $row['pid'] . "</td>";
// echo '<form action="delete.php?id2=' . $row['id'] . '" method="post">';
// drop down menu for selecting advisor as a form submission
// used to name each submit button with the id from walk_in
$formId = $row['id'] ;
echo "<td>" ;
//create a form to submit the sleected advisor and the seelcted student to be removed from the queue
echo '<form action="delete.php?id=' . $row['id'] . '" method="post">';
//another query used to retreive the list of advisors to pupulate the drop down menu
//create a drop down menu with advisors resulting from the queue
echo '<select name="formStatus">';
$con = get_sqli();
mysqli_select_db($con,"login");
$sql="SELECT * FROM login_details WHERE level = 0 AND logged = 1";
$result2 = mysqli_query($con,$sql);
if (!$result2) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
//loops through all advisors for drop down menu creation
while ($row2 = mysqli_fetch_array($result2)) {
$id = $row2['id'];
echo '<option value="'.$id.'">'.$id.'</option>';
}
echo'<option selected="selected"></option>';
echo '</select>';
echo '<td><input type="submit" name="formSubmit" value= "'.$formId.'" /><td>';
//echo '<td><input type="submit" name="formSubmit" value= /><td>';
//echo '<td>Send</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
Here are the tables i am using:
login_details table containing ADVISER details
I forgot to close the form, the issue has been fixed. Thank you all!

Issue with my PHP MySQL and AJAX code. Trying to select from a database where a name equals a variable

I was following this example found in the w3schools regarding php, mysql, and ajax. I edited the code to fit my needs, but I am unable to display information pulled from mysql. In all honesty, I'm not even sure if anything is being pulled from mysql. I do not receive any errors. The mysql database contains the id, name, and rating.
Here is my html page called results.html
<html>
<head>
<script>
function showName(str) {
if (str=="") {
document.getElementById("info").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("info").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","phpresults.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="Name" onchange="showName(this.value)">
<option value="">Select a Book:</option>
<option value="Book 1">Book One</option>
<option value="Book 2">Book Two</option>
<option value="Book 3">Book Three</option>
<option value="Book 4">Book Four</option>
</select>
</form>
<br>
<br>
<div id="info"><b>Select from above</b></div>
</body>
</html>
Here is my php page called phpresults.php
<?php
$q = strval($_GET['q']);
$con = mysqli_connect ("localhost","username","userpw");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db("dbname");
$sql="SELECT * FROM tablename WHERE name = '".$q."'";
$result = mysqli_query($sql);
echo $q;
echo "<table border='1'>
<tr>
<th>BOOK NAME</th>
<th>RATING</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["rating"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
As of right now, when I make a selection, I am only displayed with BOOK NAME and RATING and nothing underneath it. When I echo $q I am shown the value of what I selected in the dropdown. I am trying to display the name and rating of a book based on the value selected in the dropdown.
EDIT:
I believe there is something wrong with this part of the code.
$sql="SELECT * FROM tablename WHERE name = '".$q."'";
$result = mysqli_query($sql);
When checking for errors, by using this
if (!$result) {
die('Could not query: ' . mysqli_error($result));
}
I receive "Could not query:" but no error.
Your PHP code is mixing mysqli_ and mysql_ function calls.
Don't do that, because that will cause errors.
Replace those mysql_ function calls with references to the appropriate mysqli_ functions.
(And I'm not at all surprised that the w3fools site would have examples with mixed calls like this.)
I removed the $sql variable and entered the select statement directly into the mysqli_query. I also made sure that all of my function calls were mysql_ since mysqli_ was not displaying the results.
Here is my working php code.
<?php
$q = strval($_GET['q']);
$con = mysql_connect ("localhost","username","userpw");
mysql_select_db("dbname");
$result = mysql_query("SELECT * FROM tablename WHERE name = '".$q."'") or die(mysql_error());
echo $q;
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th>";
echo" <th>Rating</th>";
echo "</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["rating"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>

Form values from dropdown list not passing

I created a drop down list that has been populated by the database and now I'm having trouble retrieving the data. Normally, I would know how to retrieve the value of the drop down list if I had to manually name the data, but in this case, I'm not quite sure how I would name it.
Here is my current code:
<h1>Generate Reports</h1>
<form enctype="multipart/form-data" action="http://localhost/yiiFolder/index.php/create" method="post">
<table>
<tr>
<td><strong>Materials</strong></td>
<?php
mysql_connect('host', 'root', 'password');
mysql_select_db ("db");
$sql = "SELECT material_name FROM materials";
$result = mysql_query($sql);
echo "<td><select name='materials'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['material_name'] . "'>" .
$row['material_name'] . "</option>";
}
echo "</select></td></tr> ";
$sql2 = "SELECT location_name From locations";
$result2 = mysql_query($sql2);
?>
<td><strong>Locations</strong></td>
<?php
echo "<td><select name='locations'>";
while ($row2 = mysql_fetch_array($result2))
{
echo "<option value='" . $row2['location_name'] . "'>" .
$row2['location_name'] . "</option>";
}
echo "</select></td></tr>";
?>
<tr>
<td><button name="submit" type=submit>Generate</button></td>
</tr>
</table>
</form>
<?php
$material = $row['material_name'];
$locations = $row2['location_name'];
$generate = $_POST['submit'];
if(isset($generate))
{
echo $material;
echo $locations;
}
?>
You're trying to capture value before the submit button is hit. Also, as Hanky pointed out you're using the wrong names while referring to select data. You should do this instead
if(isset($_POST['submit'])) // this code will run after the button is clicked
{
$material = $_POST['materials']; // and not material_name
$locations = $_POST['locations']; // and not location_name
echo $material;
echo $locations;
}
PS: You're following a very unsecure way of developing a web application. At the very least you need to switch to PDO and always escape the data.

refresh = on submit in php, how to fix it?

I am creating an insert process in php but I have a problem in my code. when I refresh my page, it will also submit and insert the data.
here is my code :
<form action="/drupal/node/1" method="post">
Name: <input type="text" name="name" />
Price: <input type="text" name="price" />
Minutes: <input type="text" name="minutes" />
<input type="submit" />
</form>
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// some code
mysql_select_db("zain", $con);
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['minutes']))
{
$val_name = $_POST['name'];
$val_price = $_POST['price'];
$val_min = $_POST['minutes'];
$max_id_sql = mysql_query("SELECT MAX(id) FROM card_category");
$data = mysql_fetch_array($max_id_sql);
if ($data[0]==0)
{
$val_id = 1;
}
else
{
$val_id = $data[0] + 1;
}
mysql_query("INSERT INTO card_category (id, name, price, minutes) VALUES ($val_id,'$val_name',$val_price,$val_min )");
$_POST['name'] == NULL;
$_POST['price'] == NULL;
$_POST['minutes'] == NULL;
}
$result = mysql_query("SELECT * FROM card_category");
echo "<table border='1'>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>mins</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['minutes'] . "</td>";
echo "</tr>";
}
echo "</table>";
if (isset($_POST['lastname']))
{
print $_POST['lastname'];
}
mysql_close($con);
?>
my question is, how can I handle when I refresh the page and it will not submit the data?
thanks in advance
When you get the POST submission:
Process the data
Return a Redirect response
Get a GET request from the browser on the URL you redirect to
Respond to that with the HTML
If the browser is refreshed, it will resubmit the GET request which your PHP won't use to modify the database.
This is the POST-REDIRECT-GET pattern. There are some more details in this blog entry (which also has example PHP code in the comments).
How to fix refresh the page do not post the value using php:
if ($_SERVER['HTTP_CACHE_CONTROL']=="")
{
// process the data
}
If you look at $_SERVER['REQUEST_METHOD'] variable, it will say 'POST' when the user submitted data and 'GET' when he did not. So:
if($_SERVER['REQUEST_METHOD']=='POST')
{
// process the data
}
By the way, your code is eminently vulnerable to SQLI attacks ...

Categories