I fetched the data from my database and echoed it. Once I go to a prisoner's profile and his status is not = detained, the button 'Add Visitor' should be automatically disabled.
Where should I put my disable() function for it to be called?
Here's my script
<script language = "javascript" type = 'text/javascript'>
function disable(){
if(document.getElementById('prisonerstatus').value == "Detained"){
document.getElementById("visitorbtn").disabled= false;}
else{
document.getElementById("visitorbtn").disabled= true;
}
};
</script>
PHP
<?php
include "connect.php";
$idd =$_GET['id'];
$result = $connect->query("SELECT * FROM prisoner
INNER JOIN offensedata ON prisoner.prisoner_id = offensedata.prisoner_id
INNER JOIN arrestdata on prisoner.prisoner_id = arrestdata.prisoner_id
INNER JOIN booking ON prisoner.prisoner_id = booking.prisoner_id
WHERE prisoner.prisoner_id = $idd") or die($connect->error);
$rows1 = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows1 as $row){
$status = $row['status'];
echo "<input type = 'hidden' value = '$status' id = 'prisonerstatus'/>";
echo "<div class='col-lg-3'>Status: $status </div>";
}
Here's my button
<input type = "button" class="call_modal" style="cursor:pointer;margin-top:1%;" value = "Add Visitor" id = 'visitorbtn'>
Please excuse my code. This is for my school project only, these codes are what have been taught to us. I will study on how to avoid SQL injections and apply it soon. Thank you in advance :)
Related
I have a postgresql database for a hypothetical zoo. I am creating web access for my database using php and some javascript. I have successfully gotten the majority of the web pages to work, but am now working on a page that allows the client to add and remove animals from current exhibits. I have a dropdown that is populated with the exhibit names from the database, the second dropdown is populated from the database with animal names and their IDs that are assigned to the current exhibit selected(exhibit_id is foreign key in animal table referencing exhibit_id in exhibit table). This is dynamically changed when the exhibit name is selected. I have a third dropdown that is populated from the database with animal names and their ID that are not assigned to an exhibit. This all works upon initial loading of the page. Upon clicking the add or remove button my database is updated correctly, but the page just keeps loading. I was expecting it to give the success message and then the client could pick another exhibit and it would show the updates, but it doesn't get there. I've been teaching myself HTML, PHP, and JS so the code is pretty sloppy. I'm using some mix of examples I found on the web to get the dynamic dropdowns and ability to select multiple options from the dropdown lists so this is probably where the issue lies since I can exit the page and go back and then it will have the dropdowns with the values they should have. I would appreciate any help on why this is happening and if there are any fixes. Thanks!
<?php
//Read database info from file and assgin to variables
$myfile = fopen("../pg_connection_info.txt", "r") or die("Unable to open \"../pg_connection_info.txt\" file!");
$my_host = fgets($myfile);
$my_dbname = fgets($myfile);
$my_user = fgets($myfile);
$my_password = fgets($myfile);
fclose($myfile);
// Make a connection to the database
$dbhost = pg_connect("host=$my_host dbname=$my_dbname user=$my_user password=$my_password");
// If the $dbhost variable is not defined, there was an error
if(!$dbhost)
{
die("Error: ".pg_last_error());
}
//Get exhibits from database
$query = "SELECT exhibit_id, name FROM exhibit";
$result = pg_query($dbhost, $query);
while($row = pg_fetch_row($result))
{
$categories[] = array("id" => $row[0], "val" => $row[1]);
}
//Get animals assigned to exhibits
$query2 = "SELECT animal_id, exhibit_id, name FROM animal";
$result2 = pg_query($dbhost, $query2);
while($row = pg_fetch_row($result2))
{
$subcats[$row[1]][] = array("id" => $row[0], "val" => $row[2]);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<html lang="en-us">
<head>
<title>Manage Animals/Exhibits</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
//exhibit dropdown options
function loadCategories(){
var select = document.getElementById("exhibit");
select.onchange = updateSubCats;
var j = 0;
select.options[0] = new Option("--Select an option--");
for(var i = 0; i < categories.length; i++){
select.options[j + 1] = new Option(categories[i].val,categories[i].id);
j++;
}
}
//animals assigned to exhibits dropdown options
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("animal");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val + " - " + subcats[catid][i].id ,subcats[catid][i].id);
}
}
//Allows multiple selecting of dropdown items
window.onmousedown = function(e)
{
var el = e.target;
if(el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple'))
{
e.preventDefault();
if(el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
}
}
</script>
</head>
<body onload='loadCategories()'>
<h1>Add and Remove Animals from Exhibits</h1>
<form action="Manage_Animal_Exhibit.php" method="post">
<p>Select an exhibit to add or remove animal(s) from</p>
</select>
Exhibit: <select name="exhibit" id="exhibit">
</select><br><br>
<p>Current animals in exhibit:</p>
<select name="animal[]" id='animal' multiple>
</select><br><br>
<input type="submit" name="Remove" value="Remove"/><br><br>
<p>Current animals not assigned to an exhibit:</p>
<select name="animalAvail[]" id='animalAvail' multiple>
<?php
//get animals not in exhibit
$query3 = "SELECT name, animal_id FROM animal WHERE exhibit_id is NULL";
$result3 = pg_query($dbhost, $query3);
while($row = pg_fetch_row($result3)){
$name = $row[0];
$id = $row[1];
//Display animal's name and id in dropwdown. Assign id to the option so no need for an associative array
echo "<option value='$id'>$name - $id </option>";
}
?>
</select><br><br>
<input type="submit" name="Add" value="Add"/><br><br>
</form>
<!--Exits the Manage_Animal_Exhibit page and returns to the Home Page-->
<form action="Home_Page.php" method="post">
<input type="submit" name="Exit" value="Exit"/>
</form>
<?php
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animalAvail"] as $animalID)
{
array_push($arr, "$animalID");
}
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
for($i = 0; i < count($arr); $i++)
{
$idToUpdate = $arr[$i];
pg_execute($dbhost, "prepare1", array($exhibitID, $idToUpdate));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit')</script>";
}
}
if(isset($_POST["Remove"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
$arr2 = array();
//Get each animal selected from dropdown and add their ID to an array
foreach($_POST["animal"] as $aID)
{
array_push($arr2, "$aID");
}
$query5 = "UPDATE Animal SET exhibit_id = NULL WHERE animal_id = $1";
pg_prepare($dbhost, "prepare2", $query5);
for($i = 0; i < count($arr2); $i++)
{
$idUpdate = $arr2[$i];
pg_execute($dbhost, "prepare2", array($idUpdate));
}
echo "<script type='text/javascript'>alert('The animals were removed from the exhibit')</script>";
}
}
// Free the result from memory
pg_free_result($result);
// Close the database connection
pg_close($dbhost);
?>
</body>
</html>
I condensed my code and was able to get the web page to load immediately. The issue was within the code for updating the database when the add and also the remove button was pressed. I had an enhanced for loop to get the selected values and add them to an array and then a for loop to update the records in the database. I condensed it to just one enhanced for loop that would get the values selected and also update the database. Here is an example of what I did for the add. The remove is the same format.
//When add button is pressed assign animals to exhibit
if(isset($_POST["Add"]))
{
//If exhibit isn't selected display message
if($_POST["exhibit"] == "--Select an option--")
{
echo "<script type='text/javascript'>alert('Select an exhibit')</script>";
}
else
{
//Get id of exhibit selected and then add animals to exhibit
$exhibitID = $_POST["exhibit"];
$query4 = "UPDATE Animal SET exhibit_id = $1 WHERE animal_id = $2";
pg_prepare($dbhost, "prepare1", $query4);
foreach($_POST["animalAvail"] as $animalID)
{
pg_execute($dbhost, "prepare1", array($exhibitID, $animalID));
}
echo "<script type='text/javascript'>alert('The animals were added to the exhibit'
</script>";
}
}
Having trouble pulling variables from one PHP to another script.
I have three different files, adminPage.html, reportScript.php, and report.php.
adminPage.html takes variables from the user and uses AJAX post function to post the variables to reportScript.php.
report.php is supposed to pull those posted variables from reportScript.php and use the variables in a SQL function, however, I am receiving an error stating that I have an "undefined index: startDate" and "undefined index: endDate" where I am instantiating the variables in PHP.
adminPage.html:
<center><h2> Choose the dates below that you need an order list from: </h2>
</br>
<form>
<h2>Start:</h2>
<input type="date" id ="reportStartDate" name = "startDate">
</br>
<h2>End:</h2>
<input type="date" id ="reportEndDate" name = "endDate">
</form>
</center>
</br></br>
<button id="runReportButton" onclick = "runReport()"> Run Report </button>
<script>
function runReport()
{
var jStartDate;
var jEndDate;
jStartDate = document.getElementById("reportStartDate").value;
jEndDate = document.getElementById("reportEndDate").value;
/*console.log(jStartDate);
console.log(jEndDate); */
$.ajax
({
type: "POST",
url: "phpScripts/reportScript.php",
data: {startDate: jStartDate, endDate: jEndDate},
success: function(response)
{
console.log("posted");
window.open("report.php", "_self");
}
});
}
</script>
reportScript.php:
<?php
require 'connect.php';
//posts data to db
$startDate = $_POST["startDate"];
$endDate = $_POST["endDate"];
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < startDate OR
dateOrdered > endDate)";
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
report.php:
<?php
require 'phpScripts/connect.php';
require 'phpScripts/reportScript.php';
//posts data to db
/*$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];*/
/*$startDate = '2018-01-01';
$endDate = '2018-08-08'; */
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < '$startDate' OR dateOrdered > '$endDate');";
$result = $conn->query($sql);
//above is reportScript.php, below is pulling list method from order.php
//below works, just needs variables from the reportScript
echo "<ul>";
if($result->num_rows >0)
{
$i = 0;
while($row = $result->fetch_assoc()) // this loads database into list, also
creates array of pricing which someone can pull from later to get total
{
echo "<li style='font-size:15px'>".$row["drinkName"]. ", Date Ordered: "
.$row["dateOrdered"] . ",Cost: " .$row["drinkCost"] . "</li>";
echo "</br>";
$i = $i+1;
}
}else {
echo "<p> you're a dummy and you did this wrong </p>";
}
echo "</ol>";
?>
You forgot the dollar sign ($) in your variables in reportScript.php.
$sql = "SELECT * FROM orderlist WHERE NOT (dateOrdered < $startDate OR
dateOrdered > $endDate)";
This statement is also vulnerable to sql injection.
With some of the advice taken from #Ralf, I combined both reportScript.php and report.php, and used a $_GET statement to put the date variables into the URL upon opening. This way, the query isn't placed twice and the variables are still saved.
I want to select the last row of my table, and save all the values to separate JavaScript variables. I used the query in PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
to select the last row of the table. I don't know how to proceed.
PHP:
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
echo json_encode($row);
}
jQuery:
// sample variables
var username = "";
var password = "";
var phpUrl = 'http://sampleurl.com/mypage.php';
$.getJSON(phpUrl, function (result) {
$.each(result, function (data) {
// if data sent back is eg data:[{username:'sample', password:'sample'}]
// then you fetch and save as
username = data.username;
password = data.password;
});
});
cookies way is definitely the way to go. If you are doing all of this on one page and just need a quick fix you could do
<?php
$sql = "SELECT * from reading ORDER BY id DESC LIMIT 1";
if ($query = mysqli_query($link, $sql)) {
// fetch one result
$row = mysqli_fetch_row($query);
$json_string = json_encode($row);
}
?>
<script> var sql_row = <?php echo $json_string; ?>; </script>
This is the lazy way and will get messy quickly, but it could be useful for understanding how PHP and JS work together
we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>