Long time viewer, first time asking a question. College student new to PHP so hopefully I do this right.
I have a webpage in PHP which connects to a MYSQL db and reads back the data to the page. As the data is being read in, it populates an array. Each item that is being pulled from the db is set to a button.
Ideally, I only want to fill the array with the item that is clicked. Is it possible what I'm trying to do or is there a better alternative. I have seen that elements such as buttons are client side whereas PHP is server which (I think) indicates that I would have to refresh the page.
Thanks in advance for any help and patience!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ingredient_id, ingredient_name FROM ingredients";
$result = $conn->query($sql);
$array = array(); //used to hold each ingredient as a variable to pass to php script
array_unshift($array,"");
unset($array[0]); //our first ingredient_id is set to 1 so I've started my array at 1 to allow for that
$_SESSION['arr'] = $array;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo "<br /><button id='$row[ingredient_id]' name='button' value='button' class='btn-info btn-lg' onClick='return addItem($row[ingredient_id])'>$row[ingredient_name]</button><br />";
array_push($_SESSION['arr'],$row['ingredient_name']);
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Use javascript to get the data from the DB using an AJAX call. For the button click part, you can use jquery's on.click() function
Related
Hi there Im very new to PHP and Im having issues trying to make drop-down list with php connecting to my mysql db. I am able to connect to the database no problem as no error message is showing up when I load up the php document online.
However from my research I just cant seem to find what Im looking for. I have made a table in mysql with the necessary ids and values. Below is my code within select tags if even thats a good way to do it? if anyone can help much appreciated.
<select>
<?php
$db = mysqli_connect ("host", "username", "password");
if (!$db)
{
echo "Sorry! Can't connect to database";
exit();
}
//table name on mysql db = users3
?>
</select>
It looks like you're trying to run PHP inside of an HTML select tag. PHP runs server side (in the background).
You'll need to create your dropdown menu using Javascript and HTML, then have have your javascript code call your PHP via AJAX. There are a number of ways doing this, but the basic idea is to have an event bound to each item in your dropdown list. When you click one of your list items, your javascript uses AJAX to call your PHP which queries the database.
That's a pretty high level description of it but hopefully it gives you a sense of where you need to go from here.
Regards,
--Drew
Your code is obviously missing any SQL select query.
The following code was adapted from W3Schools, I suggest you have a read over some examples using mysqli here Mysql select query example
Included is a select list that is also courtesy of W3Schools, HTML form elements
I implore you to read some examples at W3Schools.
HTML
<select name="items"><?php echo getSelectItems(); ?></select>
PHP
<?php
function getSelectItems() {
$servername = "host";
$username = "username";
$password = "password";
$dbname = "itemDB";
$output = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemName FROM items";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$output .= '<option value="' . $i . '">' . $row["itemName"] . '</option>';
$i++;
}
}
$conn->close();
return $output;
}
I have a search box in the navigation bar of my web application that appears on every web page. I have a query that is supposed to pull results from my database based on the text the user enters in the search box but at the moment it doesn't show any results.
My web application is essentially a post it board for events so I want a user to be able to search for an event and then have that event displayed in either a table or to take it to the page of the event itself whichever is easier. I am using Netbeans as my IDE and my database is a MariaDB in XAMPP. My web application is just locally hosted for now. I currently have a query that should search the database but I think the output of the query or the result is wrong. I'm not great at PHP but just need to do this as it is in every page of the web application.
The code of the search bar on every page:
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search for an event..">
<input type="submit" value="Search">
</form>
Then the search.php file looks like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if ($conn->query($sql) === TRUE) {
echo "Result Found";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
At the moment, it just comes up saying "Connected successfullyError: SELECT eventname FROM event WHERE eventname LIKE '%Golf%'". I have an event called "SHARE Golf Classic" in the database so that's what I'm testing with currently. I would like to navigate to a page called Event.php and display the results in either a table or else fill labels or textboxes with the details of the event. The event table consists of eventid, eventname, eventtype, charityid, contactdetails, location and date.
Determining errors of objects (Mysqli) can be difficult, that's why you should use try-catch approach instead. Your code could look like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if (($result = $conn->query($sql)) === true) {
var_dump($result)
}
} catch (mysqli_sql_exception $e) {
var_dump($e)
} finally {
$conn->close();
}
Please bear in mind that using parameters from POST request in the query like this can be dangerous. I would suggest looking into a different MySQL client for PHP (PDO) and use prepared statements instead.
The code example above is also using finally, which was added in PHP 5.5, make sure your version is this or above (currently supported PHP versions are 7.2 and 7.3 - you should be always up to date).
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
Here is the page which I am working on
http://grmaedu.com/application/
The form is made using a Wordpress plugin called Visual Form Builder Pro. The form is working fine and all the data gets emailed nicely to a defined email address. Also an automatic Roll Number is generated at the time of submission.
Now my issue is, I want the roll number that is displayed "after" the form, to be emailed along with the other form values. Here is the php code that I am using to generate the roll number:
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "*****";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// get the last submitted id number
while ($row = mysqli_fetch_assoc($result)) {
$a = $row["entries_id"];
$a++; // add 1 to it for a new roll number
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
How do i make this particular below code to get submitted and emailed along with the other form values?
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
Just diving into this, the best way I'd assume is to use the VFB hooks. Either use the vfbp_form_action hook and completely replace the whole processing or use the vfbp_after_save_entry hook to save the value and somehow send it by mail.
See also https://docs.vfbpro.com/category/49-hooks
I am working on an academy website here at www.grmaedu.com
Web Specs: Built on Wordpress with the following plugins, Visual Form Builder Pro & Revolution Slider
So i have managed to do 90% of the work. My query is I want to assign automatic roll numbers to students who are submitting the application form here at www.grmaedu.com/application
Here are the remaining things I want to do:
Automatically assign Roll Number to students "after or on " form submission
Submit the form to the concerned mySql Database, Right now it emails correctly to the designated email address with no issues. All thanks to Visual Form Builder Pro
The date picker field is not working in the application form(I even updated my jQueryUI file)
I hope the provided details are enough for the solution.
I finally figured a way out. Here are the steps which i performed.
I installed a WP Plugin named Contact Form DB. This plugin saves all the form submitted values and stores them in a mySQL database.
I opened up phpmyadmin to see how it was stored and found it in one of the tables. I noticed that each entry had an unique id number. That is what I was trying to do. This plugin made it easier for me.
Then i created a Page template file name rollnumber.php and inserted the following code in
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$a = $row["entries_id"];
$a++;
echo "<h3>Your Roll Number assigned is: " . $a . "</h3>";
//echo "id: " . $row["entries_id"] . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
So now when the page loads it automatically fetches the unique id and adds 1 to the last submitted id and voila a new roll number is generated.
Index key is the best option to set as roll number. because it is unique and then you can get user data directly form this id.
<?php
/* Define Connection properties */
$servername = "localhost";
$username = "grmaedu_wp2";
$password = "******";
$dbname = "grmaedu_wp2";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT entries_id FROM `wp_vfb_pro_entries` ORDER BY entries_id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
echo "<h3>Your Roll Number assigned is: " . mysqli_insert_id() . "</h3>";
//echo "id: " . mysql_insert_id() . "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>