I have a form where I want the user to select an Organization from a SQL table and when the form is submitted, the ID of the selected organization should be saved to a different table. I researched online and on SO, and this is what I have now. And it does not work. What's wrong?
Newbrand.php:
<form action="newbrand.php" method="post">
Brand Name: <input type="text" name="bname" /><br><br>
Ogranization: <input type="text" name="searchbar" id="searchbar"><br><br>
<script>
$("#searchbar").keyup(function(){
var searchTerm = $(this).val();
$.post('search.php', { search_term: searchTerm}, function(data){
$(".searchResults").html(data);
$("#searchUl").css("display", "block");
});
});
</script>
Organization ID: <input type="hidden" name="gid" value="" /><br><br>
Gallery ID: <input type="text" name="gid" /><br><br>
</form>
Search.php:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
$search_term = sanitize(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = "(SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE '%$search_term%' LIMIT 0, 5) ";
$query = mysqli_query($link, $search);
$result = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)){
#$user_id = $row['user_id'];
#$username = $row['username'];
$orgname = $row['Organization_Name'];
$check = mysqli_num_rows($query);
if ($check != 0){
echo "<a style='text-decoration: none; color: black;' href='newbrand.php?band=$orgname'><li class='searchResults'>" . ucfirst($orgname) . "</li></a>";
} else {
echo "<li class='searchResults'>No Results Found</li>";
}
}
}
?>
The problem is with your query. It's not passing the value of $search_term, but rather passing it as a string. You may want to use prepared statements and bind the parameter first:
$stmt = mysqli_prepare($link, "SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE ? LIMIT 0, 5");
mysqli_stmt_bind_param($stmt, "s", "%{$search_term}%");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $organizaton_name);
while (mysqli_stmt_fetch($stmt)) {
}
Reference: mysqli SELECT With Prepared Statements
I searched the web for this function and found this. I copyed your source and got it working like this:
$search = "(SELECT Organization_Name FROM organizations_info WHERE Organization_Name LIKE '%". $search_term . "%' LIMIT 0, 5) ";
As you can see I changed the '%". $search_term . "%' , because you can't just place strings in sql query that is between "", you have to cut it in pieces, hope you understand now. I don't go on this site often, so it would be cool if you send me an mail if it fixed the problem to sceptdeckheroes#gmail.com, would like to hear from you, good luck.
Related
<body>
<H1>4a</H1>
<form action="hw4b.php" method="post">
<?php
$con = mysqli_connect("localhost","[credential]","","[credential]")
or die("Failed to connect to database " . mysqli_error());
?>
<select name="id" value="id">
<script>
for (x=1;x<=101;x++)
{
document.write("<option value="+x+">"+
<?php echo mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE CUSTOMERID == "+x+";")?>
+"</option>");
}
</script>
</select>
<input type="submit" value="SEND IT">
</form>
</body>
So this should put the corresponding LASTNAME into the select, but it just fills every row with "NaN". I'm sure this is some stupid minor error, but I've been staring at it too long.
you should query the results of mysqli_query
do something like this:
<select name="id" value="id">
<?php
$query = mysqli_query($con, "SELECT LASTNAME FROM CUSTOMERS WHERE WHERE CUSTOMERID >=1 and CUSTOMERID <= 101 ;");
while ($row = mysqli_fetch_array($query))
echo "<option id='".$row['LASTNAME']."'>".$row['LASTNAME']."</option>";
?>
</select>
notes:
no need for javascript usage
please escape the query parameter
id of the option is the value that will be sent to the server, makes more since to send LASTNAME
avoid using a query at a loop
Note that your for cycle is in javascript (between <script> tags), yet you try to fill in some data in php.
Everything in PHP happens on server side, i.e. is interpreted, packed into a http response and returned to the client, where it is unpacked and javascript is executed.
You need to either put both into javascript, or both into php.
<select>
<?php
for ($i = 0; $i < 100; i++){
///make some select here
echo "<option value="$i"> ...output the select </option>"
}
?>
</select>
This way, all options are generated on server side and transferred to client as text
<select>
<option value="0">...</option>
<option value="1">...</option>
...
Other option is to export the database data into javascript, and then access it in javascript.
<script>
//or perhaps better
var myOtherData = <?=json_encode($somePHPData)?>;
</script>
//now you can use for loop with document.write and one of the variables you exported...
You need to be very careful and sure which execution happens on server, and which on client side.
There are several issues I think. You are using a comparison operator in the SELECT statement, it should just be =, not ==. Also, mysqli_query returns a mysqli_result, not a value like "Johnson" for LASTNAME. And, maybe most importantly, it doesn't make sense to do this with javascript since you're writing the values to the document before sending it to the browser anyway.
The code should look something like this (not tested)
<select name="id" value="id">
<?php
$query = 'SELECT LASTNAME, CUSTOMERID FROM CUSTOMERS WHERE CUSTOMERID >= 1 AND CUSTOMERID <= 101 ORDER BY CUSTOMERID ASC';
$result = mysqli_query($con, $query);
if (!$result) {
echo 'some error handling';
} else {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row['CUSTOMERID'] . '">' . $row['LASTNAME'] . '</option>';
}
}
?>
</select>
I'm learning PHP and SQL and as exercise I'm working on a page that is actually something like admin panel for a website that lists movies. I'm using lampp and phpmyadmin where I have created a simple database that contains two tables, movie list and users list.
Because I'm beginner and my code is probably messy, I'm describing what I tried to achieve. There's login.php page where the only functionality is typing username and password. If info matches info from SQL table, user proceeds to adminpanel.php.
This page should load a list of movies and create a table with that data. At the end of each row I want two buttons, edit and delete. What I'm trying to achieve is to delete current row where delete button is clicked, for delete button. Edit button should show hidden form just for the row where button was clicked. This form would contain button that actually updates data in SQL table after filling form and clicking the button. (I haven't added function that shows form yet, I care about buttons much more) Form for adding movies at the end of the file works.
Here's adminpanel.php
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js"></script>
<script type="text/javascript" src="changes.js"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></script>
<style type="text/css">
*{text-align: center;}
.skriveni_input{
display: none;
};
</style>
</head>
<?php
require_once('connection.php');
if(!isset($_POST['btnlogin'])){
exit;
}
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT usrname,password FROM usrs WHERE usrname='$username' AND password='$password' ";
$res = mysqli_query($conn,$query);
$rows = mysqli_num_rows($res);
if($rows == 1){
echo "Welcome ".$_POST['username']."<br><br>";
} else {
echo "<script>
alert('Wrong login info');
window.location.href='login.php';
</script>";
exit;
}
$query = "SELECT * FROM movies";
$result = $conn->query($query);
echo "<table align = center cellspacing = 0 border = 0;><thead><tr><th>Name</th><th>Year</th><th>Genre</th></tr></thead><tbody>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<td id="row_id" style="display:none;" value="'.$row["movie_id"].'">'.$row["movie_id"].'</td>';
echo '<td>'.$row["name"].'</td>';
echo '<td>'.$row["year"].'</td>';
echo '<td>'.$row["genre"].'</td>';
echo '<td><input type="submit" name="edit" value="edit" data-index="' . $row['movie_id'] . '" class="btnedit" id="btnedit"></input></td>';
echo '<td><input type="submit" name="delete" value="delete" class="btndlt" id="btndlt"></input></td>';
echo "</tr>";
echo "<tr>
<td><input type='text' class='hidden_input' id='hidden_name" . $row['movie_id'] . "'placeholder='hidden name'></input></td>
<td><input type='text' class='hidden_input' id='hidden_year" . $row['movie_id'] . "'placeholder='hidden year'></input></td>
<td><input type='text' class='hidden_input' id='hidden_genre" . $row['movie_id'] . "'placeholder='hidden genre'></input></td>
</tr>";
}
echo "</tbody></table>";
?>
<h3>Add movie form: </h3>
<form action="" method="POST">
<label for="movie_name">Movie name : </label>
<input type="text" name="movie_name" id="movie_name">
<br><br>
<label for="movie_year">Year: </label>
<input type="text" name="movie_year" id="movie_year">
<br><br>
<label for="movie_genre">Genre: </label>
<input type="text" name="movie_genre" id="movie_genre">
<br><br>
<input type="submit" name="submit_movie" id="submit_movie" value="Submit">
</form>
</html>
Here's my javascript file with ajax calls:
$(document).ready(function(e){
$('#submit_movie').click(function(e){
e.preventDefault();
var movie_name = $('#movie_name').val();
var movie_year = $('#movie_year').val();
var movie_genre = $('#movie_genre').val();
$.ajax({
type: 'POST',
data: {movie_name:movie_name, movie_year:movie_year, movie_genre:movie_genre},
url: "insert.php",
success: function(result){
alert('Movie ' + movie_name + ' (' + movie_year + ')' +' added successfully.');
document.location.reload();
}
})
});
$('.btnedit').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().html();
alert(id);
//unfinished function
})
$('.btndlt').click(function(e){
var id = $(this).parent().prev().prev().prev().prev().prev().html();
e.preventDefault();
$.ajax({
type: 'POST',
data: {id:id},
url: 'delete_row.php',
success: function(result){
alert('Successfully deleted.');
document.location.reload();
}
})
})
});
Here's php page for adding a movie, insert.php (this one works, posting it just for more information) :
<?php
require_once('connection.php');
if($_REQUEST['movie_name']){
$name = $_REQUEST['movie_name'];
$year = $_REQUEST['movie_year'];
$genre = $_REQUEST['movie_genre'];
$sql = "INSERT INTO movies(name, year, genre) VALUES ('$name','$year','$genre')";
$query = mysqli_query($conn, $sql);
}
?>
Here's delete_row.php file for deleting entry with delete button:
<?php
require_once('connection.php');
$id = $_REQUEST['id'];
if(isset($_REQUEST['delete'])){
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
As you can probably see I was all over the place with php and ajax because I tried to implement multiple solutions or mix them to solve the problem.
At this stage when I click delete button I get alert message that says erasing is successful and adminpanel.php reloads with list of movies. However the movie is still there and in SQL database.
When I tried to debug delete_row.php I found out that index "id" is undefined every time even though I think I'm passing it with ajax call.
Edit
I should've said that security is not my concern right now, I do this exercise just for functionalities I described. :) Security is my next step, I am aware this code is not secure at all.
When I tried to debug delete_row.php I found out that index "id" is
undefined every time even though I think I'm passing it with ajax
call.
The reason this happens is probably because you're accessing delete_row.php directly through the browser, and because the form is not submitted (it will later through ajax) the $_REQUEST variable will always be undefined.
When debugging $_REQUEST (or $_POST) variables in the future, you should use Postman where you can actually request that php file sending your own POST arguments.
On your specific code, the query will never run because of this line:
if(isset($_REQUEST['delete']))
Which is checking for a delete variable that was never sent in the first place, hence will always resolve false
Use this code instead on delete_row.php:
<?php
require_once('connection.php');
if(isset($_REQUEST['id'])){
$id = $_REQUEST['id'];
$sql = "DELETE FROM `movies` WHERE movie_id = $id";
$query = mysqli_query($conn, $sql);
}
?>
I have this code to display a user's name:
<div><?php echo 'My name is ' . '<span id="output">' . $_SESSION['firstname'] . '</span>' ?></div>
I'd like to change what's displayed in <span id="output"></span> when a user changes their profile.
This is what I use to change their profile data in the database (shortened to only include what's needed):
<form action="" method="POST">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname">
<button type="submit" name="submit">Submit</button>
</form>
if (isset($_POST['submit'])) {
$username = $_SESSION['username'];
$query = "SELECT * FROM `users` WHERE username='$username'";
$result = mysqli_query($connect, $query) or die(mysqli_error());
$profile = mysqli_fetch_assoc($result);
$update = "UPDATE users SET firstname = '$firstname' WHERE username = '$username'";
$result2 = mysqli_query($connect, $update);
if (mysqli_query($connect, $update)) {
$_SESSION['firstname'] = $firstname;
echo 'Profile updated successfully';
}
}
The thing is, I don't know how to change the "output" to the new $_SESSION['firstname'] without refreshing the page.
I would assume that I'd need to use JQuery's ajax function, but I'm not sure how to specifically use this function to get it done.
A lot of things are wrong with the code. Besides that point here is a simple ajax request.
$('.submit').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: 'yourscript.php',
data: {firstname: $('#firstname').val()},
success: function(data){
$('#firstname').html(data);
}
});
})
And for PHP:
# 'yourscript.php',
if(isset($firstname = $_POST['firstname'])){
// do your stuff.
echo 'your new data you want to display';
} else {
echo 'something went wrong';
}
I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">
I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);
Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";
In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..