PHP: Second query does not work - php

Via post I send values to a php file that contains the following code:
// Prepare values for database
$username = $_SESSION['username'];
$event_title = $db -> real_escape_string($_POST['create_title_hidden']);
$event_type = $db -> real_escape_string($_POST['create_type_hidden']);
$event_town = $db -> real_escape_string($_POST['create_town_hidden']);
// 1. Identify users_id
$results = $db -> query("SELECT * FROM users WHERE username='$username'");
while ($result = $results->fetch_assoc()) {
$users_id = $result['id'];
}
// 2. Identify towns_id
$query = "SELECT * FROM towns WHERE town='$event_town'";
// Do Search
$results = $db -> query($query);
while ($result = $results -> fetch_assoc()) {
$towns_id = $result['id'];
}
My problem: The second query does not work, i.e. I cannot get the town_id.
I already checked my error log, there is no such error message.
Maybe there is something I forgot to include? Is it possible two have two different queries one after another in a php script?
EDITED:
Here comes my frontend with the form:
<form id="form_create_event" method="post" action="system/upload_event_tourist.php">
<p>
You can now create the event:
</p>
<!-- Forms cannot be nested inside forms, that's why the input fields from first view
need to be inserted into hidden input fields via jquery that will be transferred
via post to upload_event_tourist.php -->
<input type="hidden" id="create_title_hidden" name="create_title_hidden">
<input type="hidden" id="create_type_hidden" name="create_type_hidden">
<input type="hidden" id="create_start_hidden" name="create_start_hidden">
<input type="hidden" id="create_end_hidden" name="create_end_hidden">
<input type="hidden" id="create_picturepath_hidden" name="create_picturepath_hidden">
<input type="hidden" id="create_meetingpoint_hidden" name="create_meetingpoint_hidden">
<input type="hidden" id="create_description_hidden" name="create_description_hidden">
CREATE EVENT
<input type="submit" id="submit_create_event" name="submit_create_event">
</form>
<!-- #form_create_event -->
<script>
// Load form details into hidden input fields and Simulate click on submit
$('.button_create_event').on('click', function() {
// load form details into hidden input fields
var event_title = $('#create_title').val();
var event_type = $('#create_type').val();
var event_town = $('#create_town').val();
var event_start = $('#create_start').val();
var event_end = $('#create_end').val();
var event_picturepath = $('#create_picturepath').val();
var event_meetingpoint = $('#create_meetingpoint').val();
var event_description = $('#create_description').val();
$('#create_title_hidden').val(event_title);
$('#create_type_hidden').val(event_type);
$('#create_town_hidden').val(event_town);
$('#create_start_hidden').val(event_start);
$('#create_end_hidden').val(event_end);
$('#create_picturepath_hidden').val(event_picturepath);
$('#create_meetingpoint_hidden').val(event_meetingpoint);
$('#create_description_hidden').val(event_description);
$('#form_create_event').submit();
});
</script>

Trace out your variables.
$_POST['create_town_hidden']
is assigned by:
$('#create_town_hidden').val(event_town);
which calls the variable event_town. That variable is set here:
var event_town = $('#create_town').val();
which is supposed to select something with an id of 'create_town', but there is no element with that ID in your HTML. Fix that, and your problem is solved.

Related

How to define a variable in a foreach loop, but only when a button is clicked

I want to make an invoice, the clients are shown in a table with the foreach loop. The data is extracted from my SQL database with PDO like this:
include 'C:\xampp\htdocs\App\include\dbconnect.php';
$sql = 'SELECT * FROM clienten WHERE verzekeraar = ?';
$stmt = $database->prepare($sql);
$stmt->execute(array($_SESSION["ROL"]));
$clienten = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($clienten as $client) {
But now I have made a button in the table, and when it is pressed you get redirected to make_invoice.php and the data is converted to PDF to be printed / e-mailed etc. based on the client_ID that is in the table like this:
Polisnummer:
How do I get the $client['clientID'] to make_invoice.php when this button is clicked?
<tr><th>Create invoice </th><td><form action='make_invoice.php' method="POST">
<input type="submit" name="aanmaken" value="Click here">
</form>
</td></tr>
I have fixed this by adding
<input type="hidden" value="$client['clientID']">
to the form.

Get submit button value from multiple buttons php

I have a dynamic menu inside a form element code is here
<form method="GET" action="index.php">
<?php
display_menu(); // this function generates menu items
?>
</form>
after the menu is generated every menu item is a submit button of the above form I want to get input of a single element by name or id attribute of submit button, and load a post from database.
<form method="GET" action="index.php">
<input type="submit" name="page-1" id="page-1" value="page-1">
<input type="submit" name="page-2" id="page-2" value="page-2">
<input type="submit" name="page-3" id="page-3" value="page-3">
<input type="submit" name="page-4" id="page-4" value="page-4">
</form>
so when any input button is pressed the function display_post() is called. Code of the function is as follows:-
function display_post(){
$conn = mysqli_connect('localhost', 'root', '', 'posts') or die('cannot connect');
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$blog_post_id = $_GET["id"];
$sql = "SELECT * FROM blog_posts where id='blog_post_id' ";
$result = mysqli_query($conn, $sql) or die('cannot load');
while ($row = mysqli_fetch_assoc($result)){
if($row > 0){
echo '<div>'.$row['content'].'</div>';
}else echo 'no posts';
}
}
}
However, the display_post() method is called inside a content tag whereas the display_menu() is called inside another div.
So the problem is I'm unable to get the id of the to submit button any help will be appreciated thanks in advance.
When you click on the submit button you will get all inputs values of the form.
Do one thing put this statement print_r($_GET);exit; in display_post() as a first line and see what you get after clicking on submit button.
Note: 1. you want to get the value of clicked button then you should use javascript or jQuery and Ajax.
2. You can not get input fields value by fields ID.
ex. if we have field <input type="submit" name="page-1" id="page-1" value="page-1">
then we can get its value as:
echo $_GET['page-1'];
page-1 is the input field name.
You can make 5 different forms for each button and change the action to
action="index.php?id=1"
Then use $_GET['id']
Also change id='blog_post_id' " to id='$blog_post_id' "
If I am guessing right what is your difficulty then
$blog_post_id = $_GET['id'];
$sql = "SELECT * FROM blog_posts where id='".$blog_post_id."' ";//I modified this line
$result = mysqli_query($conn, $sql) or die('cannot load');

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.

How do I update a value in mysql using jquery, php and ajax?

HTML CODE:
<div class = "editprogramdetails" id = "editprogramblock" hidden = "true">
<?php
$programid_query = #mysql_query("select id,program_name,company,date_prog from program_details");
$row = #mysql_fetch_assoc($programid_query);
?>
ID: <input type = "textbox" id = "programnum" value = "<?php echo $row["id"] ?>" readonly/><br>
Program Name: <input type = "textbox" id = "prognameedit" placeholder = "<?php echo $row["program_name"] ?>" value = ""/><br>
Company Name: <input type = "textbox" id = "compnameedit" placeholder = "<?php echo $row["company"] ?>" value = ""/><br>
Date: <input type = "date" id = "dateedit" placeholder = "<?php echo $row["date_prog"] ?>" value = ""/><br>
<input type="button" class = "btn btn-default" id = "updatebutton" value ="Update"></input>
JQUERY CODE:
<script>
$("#updatebutton").click(function(){
var programidphp = $("#programnum").val();
var programnamephp = $("#prognameedit").val();
var companynamephp = $("#compnameedit").val();
var datephp = $("#dateedit").val();
var updaterequest = {
upprogid = programidphp;
upprognam = programnamephp;
upcompnam = companynamephp;
uppdate = datephp;
};
$.post("/TrainerApp/update_program.php", updaterequest).done(function(data){
alert(data);
}).fail(function(){
alert("Failed");
});
});
</script>
update_program.php:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
//echo $link;
if(#mysql_select_db("trainer_registration"))
{
echo "Connected successfully";
}
else
{
echo "Connection Error";
}
$upprogid = $_POST["upprogid"]
$upprognam = $_POST["upprognam"];
$upcompnam = $_POST["upcompnam"];
$uppdate = $_POST["uppdate"];
$upd_query = #mysql_query("UPDATE program_details SET program_name = '$upprognam', company = '$upcompnam', date_prog = '$uppdate' where id = '$upprogid'");
echo "Updated Successully";
?>
I am trying to update the values in the database. I don't know what mistake I am doing but I dont see any updates in the database. The username, password for the database is perfect because insertion works whereas update doesnt work. Please help.
Nota: This is too long for comments.
Firstly, there is no type = "textbox" - <input type = "textbox">
The syntax is <input type = "text">
So, change all of those to that format.
You are using # symbols often; those are error suppressors and won't help you during testing.
I suggest you remove them (for now).
Add or die(mysql_error()) to mysql_query() to see if your query is failing.
If all of those changes still don't work, you may have to add <form></form> tags with a POST method and check for errors.
Since you're using jQuery, make sure you've loaded the library and using the right doctype for it.
UPDATE is for existing data. If there is no data to update, then you may have wanted to use INSERT INTO. Only you know that.
About your Update button:
<input type="button" class = "btn btn-default" id = "updatebutton" value ="Update"></input>
You can safely remove </input> it isn't a valid closing tag.
or use type="submit" for it.
<input type="submit" class = "btn btn-default" id = "updatebutton" value ="Update">
However, you may want to use a button with a submit type for this,
Button with submit type:
<button type="submit" class = "btn btn-default" id = "updatebutton">Update</button>
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Your present code is open to SQL injection.
use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
"The username, password for the database is perfect because insertion works whereas update doesnt work."
You will need to make the comparison between those two different pieces of code in order to see what mistake you may have made.
I believe you have enough to get you started.
Final note(s):
Try running your code without the jQuery/JS and adding a form with a POST method and an action to, i.e.: <form action="/TrainerApp/update_program.php" method="post">...</form>
If it works, then you may be having path problems with $.post("/TrainerApp/update_program.php"
and may need to use something like $.post("../TrainerApp/update_program.php"
or $.post("/home/var/usr/public/TrainerApp/update_program.php" as a full system path.

Updating Game Database With PHP/Mysqli

Update
Here's my form code
<form name = "form" method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>" align = "center">
<tr><td><input type = "text" name = "command"></td></tr>
<tr><td><input type = "submit" name = "submit" value = "Enter"></td></tr>
<tr><td><input type = "submit" name = "save" value = "Save"></td></tr>
</form>
So for this school project we have to make a text based game with PHP and Mysqli, and you have to have save function where it updates the players equipment and location in the database. For some reason, I can't get mine to work. I can echo the $_SESSION['location'] and it will display the users location fine.
When I click save I don't get a query error, but it doesn't update the location in the database either. For test purposes I tried to replace $updatelocation in the query with some random letters and it updated it in the database perfectly, but I can't figure out why it won't work when I have $updatelocation = $_SESSION['location']. My save code is below.
if(ISSET($_POST['save'])) {
$updatelocation = $_SESSION['location'];
$query = "UPDATE `isu`.`game_data` SET `location` = '$updatelocation' WHERE `game_data`.`user_id` =" . $_SESSION['id'];
mysqli_query($dbc,$query) or DIE ("Query problem");
}

Categories