Retrieving Values for each line in Textarea Box - javascript

So I've came across an issue that I'm having regarding a textarea. My goal is to have a form with a textarea where a user can enter an alphanumeric name line by line and then it would pull that information from a database and display it into a table.
For example:
tt1
tt2
tt3
and on submit it would return all of the data associated with those 3 names.
I can get the textarea, parse it and get the raw values to be inserted into the sql query, but I'm getting stuck at outputting the results.
My code for now is as follows:
index.html
<form method="POST" action="getreport.php">
<div class="form-group">
<label for="textarea">Textarea</label>
<textarea class="form-control" name="textarea" id="textarea" class="textarea" rows="5" cols="50"></textarea>
</div>
<button type="submit" class="btn btn-primary" >Submit</button>
</form>
getreport.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = trim($_POST['textarea']);
$textAr = preg_split('/[\n\r]+/', $text); //<--- preg_split is where the magic happens
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
$sql = "SELECT * from guestlist WHERE guestname='$line'";
echo "$sql"; //just checking query output for now
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { //<---- take this while loop out
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>Hostname</th><th>Guestname:</th><th>date</th><th>owner</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>";
echo $row['hostname'];
echo "</td><td>";
echo $row['guestname'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['owner'];
echo "</td></tr>";
}
echo "</table>";
} //<-----as well as the closing bracket
} else {
echo "0 results";
}
$conn->close();
?>
Any help or guidance on this would be appreciated.
Thanks

Not sure your approach to the problem is the correct one, and also as someone suggested you should be worried about SQL injection. Said that, this could be one solution:
$text = trim($_POST['textarea']);
$textAr = str_replace("/n",",", $text);
$sql = "SELECT * from guestlist WHERE FIND_IN_SET(guestname,'$line')>0";
$result = $conn->query($sql);
Another way could be just iteratin every time
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$text = trim($_POST['textarea']);
$textAr = explode("/n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
$sql = "SELECT * from guestlist WHERE guestname='$line'";
echo "$sql"; //just checking query output for now
$result = $conn->query($sql);
// <---------------- ITERATE INSIDE THE FOREACH
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<table class="table table-striped table-bordered table-hover">';
echo "<tr><th>Hostname</th><th>Guestname:</th><th>date</th><th>owner</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>";
echo $row['hostname'];
echo "</td><td>";
echo $row['guestname'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['owner'];
echo "</td></tr>";
}
echo "</table>";
}
} else {
echo "0 results";
}
} // Close the foreach
$conn->close();
?>

Not sure why you used 2 while loops - fetch_assoc and mysqli_fetch_array? Each call here moves the pointer to the next row. Maybe that's why your table is not displaying correct data? It seems you can remove the fetch_assoc loop.

Related

Live data search using ajax. How to display another query when input is empty [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
$(document).ready(function(){
$("#live_search").keyup(function(){
var input = $(this).val();
if(input != ""){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
} else {
// If the input field is empty
// How display another php query here?
}
});
});
Here is the php and mysql I am trying to display when the input field is empty.
<?php
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(!$result){
die("Query Failed " . mysqli_error($db));
}
if(mysqli_num_rows($result) > 0){
?>
<h3>Policies</h3>
<ul>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<li><?php echo $s_name?> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>
<?php
}
?>
</ul>
<?php
}
?>
form_livesearch.php:
if(isset($_POST['input'])){
$input = $_POST['input'];
//to prevent from mysqli injection
// x'='x
$input = stripcslashes($input);
$input = mysqli_real_escape_string($db, $input);
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){?>
<table class="table table-bordered table-striped mt-4">
<!--
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
-->
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<tr>
<td style="font-size: 14px;"><?php echo $s_name;?> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.
So the form_livesearch.php PHP file should be something like this.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$output = "";
if(isset($_POST['input'])){
$input = $_POST['input'];
if(!empty($input)){
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$input = "%$input%"; // prepare the $input variable
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $input); // here we can use only a variable
$stmt->execute();
}else{
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
}
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows > 0){
if(empty($input))
$output = '<table class="table table-bordered table-striped mt-4"><tbody>';
else
$output = '<h3>Policies</h3><ul>';
while($row = $result->fetch_assoc()){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
if(empty($input))
$output .= '
<tr>
<td style="font-size: 14px;">' . $s_name .' <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>';
else
$output .= '<li>' . $s_name . ' <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';
}
if(empty($input))
$output .= '</tbody></table>';
else
$output .= '</ul>';
echo $output;
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You can use a separate file to handle 2 types but as they are all about products it's better to have one file.
It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.
Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.
And the html file should be something like this:
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// will execute once the page load
getData();
$("#live_search").keyup(function(){
let input = $(this).val();
getData(input);
});
});
function getData(input = ''){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
}
</script>

How would I implement pagination through php get requests

I have some code that supports pagination, but I can't make my buttons work. Can anyone help?
function setData() {
var flexContainer = document.getElementById("flex");
flexContainer.innerHTML = "<?php
foreach ($articlesarray as $seperated) {
$contentsContent = file_get_contents("../" . "$seperated[contentsname]");
echo "<div class='card'><img src='$seperated[img]'' alt='uh oh photo not found' style='width:100%''><div class='container'><h4><b>$seperated[title]</b></h4><p>$contentsContent</p></div></div>";
}
?>";
document.getElementById("back").disabled = "<?php
if ($_SERVER['REQUEST_URI'] == "/list/index.php?page=1") {
echo "true";
} else {
echo "false";
}
?>";
document.getElementById("back").style = "<?php
if ($_SERVER['REQUEST_URI'] == "/list/index.php?page=1") {
echo "display: none;";
} else {
echo "display: inline-block;";
}
?>";
}
and the php is:
$servername = "localhost";
$username = "root";
$password = "You can't have my server password";
$dbname = "myDB";
$badurl = "/list/index.php";
$newURL = "/list/index.php?page=1";
if ($_SERVER['REQUEST_URI']==$badurl) {
print "uh oh spaghettios";
header('Location: ' . $newURL);
die();
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$offsetAmount = $_GET["page"] * 9 - 9;
$sql = "SELECT id, title, contentsname, img FROM articles LIMIT 9 OFFSET $offsetAmount";
$result = $conn->query($sql);
$articlesarray = array();
while($row = mysqli_fetch_assoc($result)){
$articlesarray[] = $row;
}
//echo "<br><br><br> If you are reading this, you have found the debug screen. This website is under maintanence.";
mysqli_close($conn);
I can't work out how to add pagination using this system. Can anyone help? I have tried shifting the url but that only returned a 0 for some reason.
It's a GET request so in PHP I can just use
$_GET["page"] and then add or subtract 1 accordingly.

How to continue code to allow me to click on image and display a separate page with more info

As of right now, I am able to display my images in a single column, with an image, a title, and a small description. All of this is derived from the same database. I am not very good at coding and need some guidance, how would you add onto this existing code to 1) allow the pictures to be displayed in more than one column...and 2)allow the thumbnails to be clicked on, which will load a separate page that I can then style and list the full recipe on.
I have been messing with the code in general, and I am confused by what I created. I am not sure how to proceed.
<h2>index.php:</h2>
<section class="gallery-links">
<div class="wrapper">
<div class="gallery-container">
<?php
include_once 'includes/dbh.inc.php';
$sql = "SELECT * FROM gallery ORDER BY orderGallery DESC"
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statment failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
echo '<a href="#">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
}
?>
</div>
<?php
echo '<div class="gallery-upload">
<form action="includes/gallery-upload.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="filename" placeholder="File name...">
<input type="text" name="filetitle" placeholder="Image title...">
<input type="text" name="filedesc" placeholder="Image description...">
<input type="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>'
?>
</div>
</section>
<h2>gallery-upload.inc.php:</h2>
<?php
if (isset($_POST['submit'])) {
$newFileName = $_POST['filename'];
if (empty($newFileName)) {
$newFileName = "gallery";
} else {
$newFileName = strtolower(str_replace(" ", "-", $newFileName));
}
$imageTitle = $_POST['filetitle'];
$imageDesc = $_POST['filedesc'];
$file = $_FILES["file"];
$fileName = $file["name"];
$fileType = $file["type"];
$fileTempName = $file["tmp_name"];
$fileError = $file["error"];
$fileSize = $file["size"];
$fileExt = explode(".", $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array("jpg", "jpeg", "png");
if (in_array($fileActualExt, $allowed)) {
if ($fileError === 0) {
if($fileSize < 2000000) {
$imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt;
$fileDestination = "../images/gallery/" . $imageFullName;
include_once "dbh.inc.php";
if (empty($imageTitle) || empty($imageDesc)) {
header("Location: ../index.php?upload=empty");
exit();
} else {
$sql = "SELECT * FROM gallery;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rowCount = mysqli_num_rows($result);
$setImageOrder = $rowCount + 1;
$sql = "INSERT INTO gallery (titleGallery, descGallery, imgFullNameGallery, orderGallery) VALUES (?, ?, ?, ?);";
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL statement failed!";
} else {
mysqli_stmt_bind_param($stmt, "ssss", $imageTitle, $imageDesc, $imageFullName, $setImageOrder);
mysqli_stmt_execute($stmt);
move_uploaded_file($fileTempName, $fileDestination);
header("Location: ../index.php?upload=success");
}
}
}
} else {
echo "File size is too big!";
exit();
}
} else {
echo "You had an error!";
exit();
}
} else {
echo "You need to upload a proper file type!";
exit();
}
<h2>dbh.inc.php:</h2>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "gallery";
$conn = mysqli_connect($servername, $username, $password, $dbname);
Basically, you need to make a link on anchor tag which will have url of image detailed page with image id as below:
while ($row = mysqli_fetch_assoc($result)) {
// assuming that imgId is your primary key
echo '<a href="detail.php?imageId="'.$row["imgId"].' target="_blank">
<div style="background-image: url(img/gallery/'.$row["imgFullNameGallery"].');"></div>
<h3>'.$row["titleGallery"].'</h3>
<p>'.$row["descGallery"].'</p>
</a>';
}
After, you need to create a new file detail.php where you can get image id by $_GET['imgId'] and then can query on that and will be able to get complete image details. You will also need to create a HTML for view and can show details.
Hope it helps you!!

Receiving multiple values back from Ajax using JSON, without JQuery, not working

I'm just trying Ajax for the first time, with PHP, and I'd like to avoid using JQuery for now.
I got it to send back 1 list of states wrapped in a drop down element. woo hoo!
Now when I added JSON to return 2 values to be parsed back out (wrapped in an array - one a string, and one am array), it's not working. I suspect that the data is getting passed around property, but a headers-warning-message is being appended at the front of the return req so the entire string can't properly be parsed. Seems to be just a header issue of some sort. I'm not familiar with header stuff so I'm not sure where to go next. I have now pasted that content below.
Main Page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($con->connect_error)
{
die("Connection failed");
}
$sql = 'SELECT country_name, country_id
FROM countrylist
ORDER BY 1';
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
//Create entry form on page
echo
"<form action = 'searchresults.php' method='post'>
<h1>FIND A PET SITTER</h1>
<br/>
Enter either a ZipCode
<table>
<tr>
<td style='text-align:right'>
Zip Code:
</td>
<td>
<input name='search_zip'></input>
</td>
</tr>
<br/><br/>
Or Country, City, and State
<tr>
<td style='text-align:right'>";
echo "Country: <td>
<select onChange='getState(this.value)' name='search_country' value=''>";
while ($row = $result->fetch_assoc())
{
if ($row[country_name] == 'United States of America')
{
echo "<option value ='".$row['country_id']."' selected>".$row['country_name']." </option>
";
}
else
{
echo "<option value='".$row['country_id']."'> ".$row['country_name']."</option>
";
}
}
echo
"
</select>
</td>
</tr>
<tr>
<td style='text-align:right'>
City:
</td>
<td>
<input name='search_city'>
</input>
</td>
</tr>
<tr>
<td style='text-align:right'>
<div id='statelab'></div>lab
</td><td>
<div id='statediv'></div>div
</td>
</tr>
</table>
<input type='submit'>
</input>
</form>";
?>
<script>
function getState(countryId) {
var strURL="getStates.php?countryIn="+countryId;
var req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) { //if success
alert(req.responseText);
var obj = JSON.parse(req.responseText);
document.getElementById('statediv').innerHTML=obj.stateselectbox;
document.getElementById('statelab').innerHTML=obj.statelabel;
}
else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
getState(230);/*united states*/
</script>
Ajax calls this page:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countryId = intval($_GET["countryIn"]);
if ($countryId < 1 || $countryId > 1000) exit();
$sql = 'SELECT divisions_are_called
FROM countrieslist
WHERE country_id = 0'.$countryId ;
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$divisionsAreCalled = $row[divisions_are_called];
//echo $divisionsAreCalled.': </td><td>';
$sql = 'SELECT state_name
FROM stateslist
WHERE state_name <> ""
AND country_id = 0'.$countryId . '
ORDER BY 1' ;
$result = mysqli_query($con, $sql);
$stateSelectBox = '<select name="statename">';
while ($row = mysqli_fetch_assoc($result))
{
$stateSelectBox=$stateSelectBox. '<option value="'.$row["state_name"].'">'.$row["state_name"].'</option>';
}
$stateSelectBox=$stateSelectBox. '</select>';
$data=array('divisionsarecalled'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
//header('Content-Type: application/javascript');
header('Content-Type: application/json');
echo JSON_encode($data);
?>
Here is the response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/professional/www/dan/myFiles/getStates.php:2) in <b>/home/professional/www/dan/myFiles/getStates.php</b> on line <b>43</b><br />
{"statelabel":"State","stateselectbox":"<select name=\"devices\"><option value=\"Alabama\">Alabama<\/option><option value=\"Alaska\">Alaska<\/option><option value=\"American Samoa\">American Samoa<\/option><option value=\"Arizona\">Arizona<\/option><option value=\"Arkansas\">Arkansas<\/option><option value=\"Armed Forces Americas\">Armed Forces Americas<\/option><option value=\"Armed Forces Europe\">Armed Forces Europe<\/option><option value=\"Armed Forces Pacific\">Armed Forces Pacific<\/option><option value=\"California\">California<\/option><option value=\"Colorado\">Colorado<\/option><option value=\"Connecticut\">Connecticut<\/option><option value=\"Delaware\">Delaware<\/option><option value=\"Florida\">Florida<\/option><option value=\"Georgia\">Georgia<\/option><option value=\"Guam\">Guam<\/option><option value=\"Hawaii\">Hawaii<\/option><option value=\"Idaho\">Idaho<\/option><option value=\"Illinois\">Illinois<\/option><option value=\"Indiana\">Indiana<\/option><option value=\"Iowa\">Iowa<\/option><option value=\"Kansas\">Kansas<\/option><option value=\"Kentucky\">Kentucky<\/option><option value=\"Louisiana\">Louisiana<\/option><option value=\"Maine\">Maine<\/option><option value=\"Maryland\">Maryland<\/option><option value=\"Massachusetts\">Massachusetts<\/option><option value=\"Michigan\">Michigan<\/option><option value=\"Minnesota\">Minnesota<\/option><option value=\"Mississippi\">Mississippi<\/option><option value=\"Missouri\">Missouri<\/option><option value=\"Montana\">Montana<\/option><option value=\"Nebraska\">Nebraska<\/option><option value=\"Nevada\">Nevada<\/option><option value=\"New Hampshire\">New Hampshire<\/option><option value=\"New Jersey\">New Jersey<\/option><option value=\"New Mexico\">New Mexico<\/option><option value=\"New York\">New York<\/option><option value=\"North Carolina\">North Carolina<\/option><option value=\"North Dakota\">North Dakota<\/option><option value=\"Northern Mariana Islands\">Northern Mariana Islands<\/option><option value=\"Ohio\">Ohio<\/option><option value=\"Oklahoma\">Oklahoma<\/option><option value=\"Oregon\">Oregon<\/option><option value=\"Pennsylvania\">Pennsylvania<\/option><option value=\"Puerto Rico\">Puerto Rico<\/option><option value=\"Rhode Island\">Rhode Island<\/option><option value=\"South Carolina\">South Carolina<\/option><option value=\"South Dakota\">South Dakota<\/option><option value=\"Tennessee\">Tennessee<\/option><option value=\"Texas\">Texas<\/option><option value=\"U.S. Virgin Islands\">U.S. Virgin Islands<\/option><option value=\"Utah\">Utah<\/option><option value=\"Vermont\">Vermont<\/option><option value=\"Virginia\">Virginia<\/option><option value=\"Washington\">Washington<\/option><option value=\"Washington DC\">Washington DC<\/option><option value=\"West Virginia\">West Virginia<\/option><option value=\"Wisconsin\">Wisconsin<\/option><option value=\"Wyoming\">Wyoming<\/option><\/select>"}
EDIT: I added changed these 3 lines in the page ajax calls and it works now:
<?php
ob_start(); //<--ADDED THIS
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xx ...
...$data=array('statelabel'=>$divisionsAreCalled,
'stateselectbox'=>$stateSelectBox);
header('Content-Type: application/javascript');
//echo json_encode($data); //<--CHANGED THIS TO THE 2 LINES BELOW
ob_end_clean(); // this clears any potential unwanted output
exit(json_encode($data));
?>

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