I have a selector wich gets information from the database. But when my database table is empty, the selector still shows up like this:
However, when my database is empty. I don't want to show the selector. but a message that says something like: Database is empty! Add something.
My code for the selector:
$results = $database->Selector();
echo "<form name='form' method='POST' id='selector'>";
echo "<select name='train_name' id='train_name' multiple='multiple'>";
// Loop trough the results and make an option of every train_name
foreach($results as $res){
echo "<option value=" . $res['train_name'] . ">" . $res['train_name'] . "</option>";
}
echo "</select>";
echo "<br />" . "<td>" . "<input type='submit' name='Add' value='Add to list'/>" . "</td>";
echo "</form>";
The function:
function selector() {
$sql = "SELECT train_name, train_id FROM train_information ORDER BY train_name";
$sth = $this->pdo->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
EDIT:
Got this now:
$results = $database->Selector();
if(count($results) > 0) {
//Form etc here//
}else echo "nope";
It is working now! :D
Related
I have a mysql database table called "names" as per below :
All columns (other than id) are stored as varchar
There is a full .php URL stored in Column "Full Name" for each record but I am getting a stackoverflow code error when using the URL in table below.
id
First Name
Surname
Full Name
Profile
1
John
Smith
John Smith
.PHP URL stored as a text string
2
Jane
Doe
Jane Done
.PHP URL stored as a text string
3
Prakash
Singh
Prakash Singh
.PHP URL stored as a text string
I have some mysql and php that returns the records for the first four columns and puts them into a bootstrap table :
<?php
// Include config file
require_once "conn.php";
// Attempt select query execution
$sql = "SELECT * FROM names";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-dark table-hover table-bordered table-striped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo '<th>First Name</th>';
echo "<th>Surname</th>";
echo '<th>Full Name</th>';
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['First Name'] . "</td>";
echo "<td>" . $row['Surname'] . "</td>";
echo "<td>" . $row['Full Name'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close connection
mysqli_close($link);
?>
What I would like to do:
Make all cell's in Column "Full Name" to be independently clickable.
Onclick, I would like to take the user to the respective profile URL of the record id without opening a new page.
Attempts:
I added a class to the td for Full Name for an onclick event :
echo "<td class='clickme'>" . $row['First Name'] . "</td>";
This made only the first row of the table clickable.
I added some javascript for the class :
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var myVar = window.location.replace("https://www.stackoverflow.com");
};
This partially worked, the page refreshes and redirects to the URL provided. However, as each record has it's own URL (stored in the database) I'd like to retrieve the specific URL rather than input an absolute URL here.
Thanks alot in advance for any help rendered!
I never worked with php but in plane html js. you can pass your url through data attibute.
<td class='clickme' data-url="your_cell_url"> First Name </td>
and then in js file
var myMap = document.getElementById("clickme");
myMap.onclick = function() {
var url = this.dataset.url
var myVar = window.location.replace(url);
};
i think it may helps
Try:
echo "<td>" . $row['First Name'] . "</td>";
or if you're using get method for profile page it will look something like this:
echo "<td>" . $row['First Name'] . "</td>";
I have a dropdown <select> HTML menu created from a MySQL table using PHP. Each <option> value contains a socket, I have a HTML table created from a MySQL table using PHP which contains a column "Socket". I want to filter the table to only show matching sockets to the one selected in the <select> menu.
I have tried modifying Javascript search code to no success.
The code for the table creation is:
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td><a href='https://au.pcpartpicker.com/product/".$row["id"]."' target='_blank'>" . $row["name"]. "</a></td><td>" . $row["price"]."</td><td>" . $row["socket"]."</td><td>" . $row["chipset"]."</td><td>" . $row["ramslots"]."</td><td>" . $row["maxram"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
The code for the <select> menu is:
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value='CPU'>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='".$row["socket"]."'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
Here is the link to the entire webpage code: pastebin.com/WztPQzRG
cpu SQL fiddle: db-fiddle.com/f/teZxiaduNVjuYCj1pWjj73/0
motherboard SQL fiddle: db-fiddle.com/f/pSs8yKNrgTqtiwdTbmWcg/0
Update: Here is my PHP
$sql = "SELECT name, socket FROM cpu";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<select name='CPUmenu'>";
echo "<option value=''>CPU</option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='". $row["socket"] . "'>".$row["name"]."</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$sql = "SELECT name, price, id, socket, ramslots, maxram, chipset FROM motherboard";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
echo "<table id='myTable'><tr><th>Motherboard</th><th>Price</th><th>Socket</th><th>Chipset</th><th>Ram Slots</th><th>Max Ram</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
}
echo "</table>";
} else {
echo "0 results";
}
Update 2:
I have tried troubleshooting by adding:
echo "<option value='AM4'>AM4</option>";
echo "<option value='LGA1151'>LGA1151</option>";
And
echo "<tr data-socket='AM4'><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
However nothing happens still. All I can think is the script isn't added right or something; here it is:
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
</script>
</body>
</html>
What other troubleshooting steps can I take?
I need to get a Javascript function which runs whenever a new option is selected from the <select> menu, the function needs to get the selected <select> menu socket name then loop through each row in the table and check if the socket matches, otherwise hide the row.
Start by adding something into the table row to identify the socket. Let's use a data attribute:
echo '<tr data-socket="'. $row['socket'] . '"><td>' . $row['name'] . '</td><td>' . $row['price'] . '</td><td>' . $row['socket'] . '</td><td>' . $row['chipset'] . '</td><td>' . $row['ramslots'] . '</td><td>' . $row['maxram'] . '</td></tr>';
Also change your default option line to this
echo "<option value=''>CPU</option>";
I'm going to suggest that you use jQuery because it's going to make your life easier. So add just before the close of your body tag
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Then you need to create a listener for the select to change and then hides anything that doesn't match the selected CPU socket. Put this right AFTER the script tag above that included the jQuery library.
<script>
$(function() {
$('select[name="CPUmenu"]').change(function(e) {
let socket = $(this).val();
$('tr[data-socket]').show();
if (socket.length) {
$('tr[data-socket!="' + socket + '"]').hide();
}
});
});
</script>
I've made an attempt at using radio buttons to control my mysql query, however I have hit some beginner roadblocks. I've either got minor typos or setup this up all wrong.
(1) I've set the displayed value of the radio buttons to be the result of query A by using an array. This is working fine.
(2) I've also set the array value to be the value of that radio button, while all radio buttons have the same name. I'm under the assumption this will allow the radio button name to serve as a variable to pass into query B, however I set the radio button name ('rbreed') to be equal to a variable and then used the variable($choice) in query B.
I noticed that when I view the page for the first time, no buttons are checked by default and it's likely the variable is null and therefore the query is null and the page doesn't work. Additionally, if I click on one of the buttons, it still yields no result and the selected button becomes un-selected.
I've created an if else statement to deal with this and change the query slightly, but am stuck with "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\NS\view.php on line 59"
Here is my code
<?php
$con = mysqli_connect("localhost","Nibbs","password");
if (!$con) {
die ("You have a connect error: " . mysqli_connect_error());
}
mysqli_select_db($con,"Dogs");
$choice = 'rbreed';
if ($choice = '') {
$sql = "SELECT * FROM register";
$myData = mysqli_query($con,$sql);
mysqli_query($con,$sql);
} else {
$sql = "SELECT * FROM register WHERE hounds = $choice";
$myData = mysqli_query($con,$sql);
mysqli_query($con,$sql);
}
$radiosql = "SELECT DISTINCT Breed FROM register";
$myRData = mysqli_query($con,$radiosql);
$myRarray = array();
while ($row = mysqli_fetch_array($myRData,MYSQL_ASSOC)){
$myRarray[] = $row;
}
echo "Select your type of hound:";
echo "<br />";
echo "<br />";
echo "<form action='' method='post'>";
echo "<input type='radio' name='rbreed' value=''>All";
echo "<input type='radio' name='rbreed' value=" . $myRarray[0]['Breed'] . ">" . $myRarray[0]['Breed'];
echo "<input type='radio' name='rbreed' value=" . $myRarray[1]['Breed'] . ">" . $myRarray[1]['Breed'];
echo "<input type='radio' name='rbreed' value=" . $myRarray[2]['Breed'] . ">" . $myRarray[2]['Breed'];
echo " "."<input type='submit' name='submit' value='Select' />";
echo "</form>";
echo "<br />";
echo "<table border=1>
<tr>
<th>Register ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Breed</th>
<th>Weight</th>
<th>Age</th>
<th>Sex</th>
</tr>";
while($record=mysqli_fetch_array($myData)){
echo "<tr>";
echo "<td><input type='text' name='reg_id' value='" . $record['reg_id'] . "'/> </td>";
echo "<td><input type='text' name='first_name' value='" . $record['First_Name'] . "'/> </td>";
echo "<td><input type='text' name='last_name' value='" . $record['Last_Name'] . "'/> </td>";
echo "<td><input type='text' name='breed' value='" . $record['Breed'] . "'/> </td>";
echo "<td><input type='int' name='weight' value='" . $record['Weight'] . "'/> </td>";
echo "<td><input type='int' name='age' value='" . $record['Age'] . "'/> </td>";
echo "<td><input type='text' name='sex' value='" . $record['Sex'] . "'/> </td>";
echo "</tr>";
}
first change
if ($choice = '') {
$sql = "SELECT * FROM register";
$myData = mysqli_query($con,$sql);
mysqli_query($con,$sql);
}
into
if ($choice == '') {
$sql = "SELECT * FROM register";
$myData = mysqli_query($con,$sql);
mysqli_query($con,$sql);
}
and before while loop you must check num_rows > 0
$rowcount=mysqli_num_rows($myData);
if($rowcount > 0 )
{
while ($row = mysqli_fetch_array($myRData,MYSQL_ASSOC)){
$myRarray[] = $row;
}
}
Change
$sql = "SELECT * FROM register WHERE hounds = $choice";
to
$sql = "SELECT * FROM register WHERE hounds = '". mysqli_real_escape_string($choice). "'";
Otherwise it's an SQL syntax error.
So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle
Hello fellow programmers!
I'm working on a personal project (mainly to learn php/javascript) and have ran into an issue with redirection when clicking on a link. I have a bit of a strange situation on a tabbed page I've created and I think that may be what is causing my problem.
I'm trying to allow the user to click the (which due to css has made it look different than normal ) to redirect them to a new page with more details. I THINK that the second tag on my page is what is throwing me off because I have a form in it.
I have tried tons of different things like window.location.href="", location.href="", document.location="", etc... But the same thing always occurs. I am able to get both alert messages, so I know I am getting into my JavaScript (even when I put it into it's own .js file).
Anyway advice/help would be very helpful. Also, if anyone has a suggestion on cleaning this code up a bit, that would also be truly helpful.
Below is basically what I have.
Thanks in advance for your help!
<html>
<head>
<title>test site</title>
<link rel="stylesheet" href="test.css" type="text/css" media="screen" />
<script src="test.js" type="text/javascript"></script>
<script type="text/javascript">
function viewDetails(modelId){
alert(modelId);
window.location.href="new url?ModelID=" + modelId;
alert('redirecting would be way awesome...');
}
</script>
</head>
<body onload="load()">
<div id="tabbed_box_1" class="tabbed_box">
<h4>Navigation Tabs<small>Select a tab</small></h4>
<div class="tabbed_area">
<?php
mysql_connect('host','user','password');
mysql_select_db("database");
echo "<ul class='tabs'>";
echo "<li><a href='javascript:tabSwitch(1, 2);' id='tab_1' class='active'>Inventory</a></li>";
echo "<li><a href='javascript:tabSwitch(2, 2);' id='tab_2' >Add Project</a></li>";
echo "</ul>";
echo "<div id='content_1' class='content'>";
echo "<ul>";
$modelsSQL = "SELECT * FROM Model ORDER BY Name";
$modelsResult = mysql_query($modelsSQL);
while ($modelRow = mysql_fetch_array($modelsResult)){
$modelID = $modelRow[0];
$sqlAvailCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 0";
$sqlSoldCount = "SELECT * FROM Project WHERE ModelID = " . $modelID . " AND Sold = 1";
$resultAvailCount = mysql_query($sqlAvailCount);
$resultSoldCount = mysql_query($sqlSoldCount);
$rowAvailCount = mysql_num_rows($resultAvailCount);
$rowSoldCount = mysql_num_rows($resultSoldCount);
echo "<li><a href='' onclick='javascript:viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>"
. $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
}
echo "</ul>";
echo "</div>";
echo "<div id='content_2' class='content'>";
echo "<form action='project_insert.php' method='post' name='projectAddForm'>";
echo "<table cellpadding='5'>";
// Project Model Selection
echo "<tr><td>";
echo "<label for='model'>Model</label>";
echo "</td><td>";
echo "<select name='model' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$modelListSQL = "SELECT * FROM Model ORDER BY Name";
$modelListResult = mysql_query($modelListSQL);
while ($modelListRow = mysql_fetch_array($modelListResult)){
echo "<option value='" . $modelListRow['ID'] . "'>" . $modelListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Material Selection
echo "<tr><td>";
echo "<label for='material'>material</label>";
echo "</td><td>";
echo "<select name='material' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$materialListSQL = "SELECT * FROM Material ORDER BY Name";
$materialListResult = mysql_query($materialListSQL);
while ($materialListRow = mysql_fetch_array($materialListResult)){
echo "<option value='" . $materialListRow['ID'] . "'>" . $materialListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Finish Selection
echo "<tr><td>";
echo "<label for='finish'>finish</label>";
echo "</td><td>";
echo "<select name='finish' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$finishListSQL = "SELECT * FROM Finish ORDER BY Name";
$finishListResult = mysql_query($finishListSQL);
while ($finishListRow = mysql_fetch_array($finishListResult))
{
echo "<option value='" . $finishListRow['ID'] . "'>" . $finishListRow['Name'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
// Project Craftsman Selection
echo "<tr><td>";
echo "<label for='craftsman'>craftsman</label>";
echo "</td><td>";
echo "<select name='craftsman' style='width: 250px;'>";
echo "<option value='-1' selected>SELECT</option>";
$craftsmanListSQL = "SELECT * FROM Craftsman ORDER BY FirstName";
$craftsmanListResult = mysql_query($craftsmanListSQL);
while ($craftsmanListRow = mysql_fetch_array($craftsmanListResult)){
echo "<option value='" . $craftsmanListRow['ID'] . "'>" . $craftsmanListRow['FirstName'] . " " . $craftsmanListRow['LastName'] . "</option>";
}
echo "</select>";
echo "</td></tr>";
//Project Description
echo "<tr><td>";
echo "<label for='description'>Description</label>";
echo "</td><td>";
echo "<input type='text' name='description' id='textArea' style='width:250px'>";
echo "</td></tr>";
// Project Selling Price
echo "<tr><td>";
echo "<label for='price'>Price</label>";
echo "</td><td>";
echo "<input id='price' name='price' type='number' style='width:150px'>";
echo "</td></tr>";
// Project Completion Date
echo "<tr><td>";
echo "<label for='date'>Finish Date</label>";
echo "</td><td>";
$dateArray = getdate();
$month = $dateArray[mon];
$day = $dateArray[mday];
if ($month < 10){
$month = '0' . $dateArray[mon];
}
if ($day < 10){
$day = '0' . $dateArray[mday];
}
$todaysDate = $dateArray[year] . '-' . $month . '-' . $day;
echo "<input type='date' name='date' value='" . $todaysDate . "' style='width:150px'>";
echo "</td></tr>";
// Buttons
echo "<tr><td align='center'>";
echo "<input type='button' name='Save' value='Save' onclick='javascript:validateAndSubmit(this.form);' style='width:100px'>";
echo "</td><td align='center'>";
echo "<input type='button' name='Cancel' value='Cancel' onclick='javascript:cancelEntry();' style='width:100px'>";
echo "</td></tr>";
echo "</table>";
echo "</form>";
echo "</div>";
?>
</div>
</div>
</body>
window.location.href may not trigger reload in some browsers and cases..
You should add a reload after
like this:
window.location.href = '/foo/bar/';
window.locaton.reload(true)
But, some browsers delay milliseconds to perform location.href set. In this cases the window.location.reload(true) may complete before this.
Therefore, add a timeout in reload:
window.location.href = '/foo/bar/';
setTimeout('window.locaton.reload(true)', 500);
works in all browsers for me
Good morning! I found the cause of my problem this morning and have been able to resolve the issue. The problem I was causing is because I am using the tag (stylized by css) to display the information, with an onclick event to call my JS code to redirect. Within the tag I had the href='', thinking that the JS would override that functionality, it doesn't!
Removing the href='' from the tag resolved the issue and allowed me to redirect to the new page. A second solution is to use my php code to dynamically create the href link within the tag.
echo "<li><a onclick='viewDetails($modelID);'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
OR
echo "<li><a href='inventorydetails.php?ModelID=" . $modelID . "'>" . $modelRow[1] . "<small>in stock: <value>" . $rowAvailCount . "</value> sold: <value>" . $rowSoldCount . "</value></small></a></li>";
I think I will go with the second example for two reasons. First, it provides the link icon when hovering (which I know I can add through css, but this is easier. Second, less JS code.
I thank you for all your help in resolving this!