Pass radio button value to mysql query - javascript

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.

Related

Editable table without using jquery plugins

I want to create a table with editable contents(using an "edit" button on each row), without the use of Bootstrap, or any other plugin.
I want to only use HTML,PHP,AJAX,JavaScript. Is this kind of task possible, and if so, can someone post some sample code or example?
SQL results work fine.
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
$role_name = 'role_name';
while($rows = mysqli_fetch_array($result))
{ echo "<tr>";
echo "<td> $rows[$user_id]</td>";
echo "<td> $rows[$name]</td>";
echo "<td> $rows[$surname]</td>";
echo "<td> $rows[$username]</td>";
echo "<td> $rows[$password]</td>";
echo "<td> $rows[$role_name]</td>";
?>
<div id = "edit">
<td> <button type='button' id="<?php $rows[$user_id];?>" onclick="submit_id()"> Edit </button> </td>
</div>
<?php
}
echo "</table>"; ?>
<script>
function submit_id() {
var user_id = user_id.val();
$.ajax({
url:'reedit.php',
type: 'GET',
data: (user_id);
})
}
</script>
I want to have each edit button, to change only the row that it is aligned to.
I saw that you had jQuery at least..
I think this will help you a LOT:
<?php
$sql_query = "SELECT User.user_id,User.name,User.surname,User.username,User.password,Role.role_name FROM User INNER JOIN Role ON User.role_id = Role.role_id";
$result = mysqli_query($conn, $sql_query);
if(!$result) {
die(mysqli_error($conn));
}
$table_html = "<table id=\"usersTable\">";
while($rows = mysqli_fetch_array($result)) {
$table_html .= "<tr>";
$table_html .= "<td>" . $rows["user_id"] . "</td>";
$table_html .= "<td>" . $rows["name"] . "</td>";
$table_html .= "<td>" . $rows["surname"] . "</td>";
$table_html .= "<td>" . $rows["username"] . "</td>";
$table_html .= "<td>" . $rows["password"] . "</td>";
$table_html .= "<td>" . $rows["role_name"] . "</td>";
$table_html .= "<td><button type=\"button\" class=\"editBnt\">Edit</button></td>";
$table_html .= "</tr>";
}
$table_html .= "</table>";
echo $table_html;
?>
<script>
$(function() {
$("#usersTable").on("dblclick", "td td:not(:first-child) td:not(:last-child)", function() {
$(this).html("<input type=\"text\" class=\"form-control dynamicInput\" value=\""+$(this).text()+"\"></input>").children("input").focus();
$(this).on("change blur", "input.dynamicInput", function() {
$(this).parent("td").text($(this).val());
});
});
$("#usersTable").on("click", "button.editBnt", function() {
var row = $(this).parent().parent(),
user_data = {
user_id: row[0].cells[0].innerText,
name: row[0].cells[1].innerText,
surname: row[0].cells[2].innerText,
username: row[0].cells[3].innerText,
password: row[0].cells[4].innerText,
role_name: row[0].cells[5].innerText
};
alert("You can now save the data or do what ever you want here.. check your console.");
console.log(user_data);
});
});
</script>
you can use the content-editable attribute to make your cells editable
something like:
var rows = document.querySelectorAll("tr");
row.foreach(function() {
this.addEventListener('click', function() {
this.setAttribute('contenteditable','contenteditable');
});
});
You will want to put the click listener on your button instead of the row

Alerting only 1st Product Code from table?

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

Oop check if database table is empty

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

Ajax function can't get int valor onclick javascript

I have a function on ajax that retrieves the int on the input button onclick, this is the javascript ajax code:
function checkBoxes(str){
var xmlhttp=browsers();
if(str=""){
document.getElementById("txt").innerHTML="";
return;
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php?h"+str,true);
xmlhttp.send();
}
I use php to print the results on the screen, with an onclick button:
if(isset($_GET['k'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
$k=intval($_GET['k']);
$sql3=oci_parse($con, "SELECT TARIFAS.ID, TARIFAS.ID_TIPO_ACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, TIPO_ACTIVIDAD
WHERE TARIFAS.ID_TIPO_ACTIVIDAD=TIPO_ACTIVIDAD.ID
AND TARIFAS.ID_TIPO_ACTIVIDAD=$k");
oci_execute($sql3);
echo "<div class='divPrecios'>";
echo "<table border='1'>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Tipus Tarifa</td>
<td>Temps/Km</td>
<td>Preu</td>
<td><input type='button' class='carrito' value=''></td>";
echo "</tr>";
while (($row=oci_fetch_array($sql3,OCI_BOTH))!=false){
echo "<tr>";
echo "<td>".$row['TIPO']."</td>";
echo "<td>".$row['TEMPS_KM']."</td>";
echo "<td>".$row['PRECIO']."</td>";
echo "<td>".$row['ID']."</td>";
echo "<td><input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."'/></td>";
echo "</tr>";
}
echo "</table>";
echo "</div>";
}
I thougt there is the error:
input type='button' name='checkbox[]' onclick=checkBoxes('".$row['ID']."') value='".$row['ID']."';
I do tests and if I pass a single int valor, it returns 0... why??
So the table with the result if all it's correct:
if(isset($_GET['h'])){
$con=oci_connect('jvillegas','1234','XE');
if(!$con){
die("No s'ha pogut connectar: ".mysqli_error($con));
}
echo "<table border=1>";
echo "<tr class='tabPreciosTitles'>";
echo "<td>Nom Activitat</td>
<td>Nom Tipus Activitat</td>
<td>Tipus Tarifa</td>
<td>Temps/km</td>
<td>Preu</td>";
echo "</tr>";
$h=intval($_GET['h']);
$sql4=oci_parse($con, "SELECT ACTIVIDAD.NOM AS NOM_ACTIVIDAD, TIPO_ACTIVIDAD.NOM AS NOM_TACTIVIDAD, TARIFAS.TIPO, TIPO_ACTIVIDAD.TEMPS_KM, TARIFAS.PRECIO
FROM TARIFAS, ACTIVIDAD, TIPO_ACTIVIDAD
WHERE TARIFAS.ID=$h
AND TARIFAS.ID_TIPO_ACTIVIDAD = TIPO_ACTIVIDAD.ID
AND TIPO_ACTIVIDAD.ID_ACTIVIDAD = ACTIVIDAD.ID");
oci_execute($sql4);
$array=array(
0=>array(),
1=>array(),
2=>array(),
3=>array(),
4=>array()
);
while (($row=oci_fetch_array($sql4,OCI_BOTH))!=false){
array_push($array[0],$row['NOM_ACTIVIDAD']);
array_push($array[1],$row['NOM_TACTIVIDAD']);
array_push($array[2],$row['TIPO']);
array_push($array[3],$row['TEMPS_KM']);
array_push($array[4],$row['PRECIO']);
}
for ($x=0;$x<count($array[4]);$x++){
echo "<tr>";
echo " <td>".$array[0][$x]."</td>";
echo " <td>".$array[1][$x]."</td>";
echo " <td>".$array[2][$x]."</td>";
echo " <td>".$array[3][$x]."</td>";
echo " <td>".$array[4][$x]."</td>";
echo " <td><input type='submit' class='carritoElim' value=''></td>";
echo "</tr>";
}
echo "</table>";
}
And to show these results I use divs:
<div id='txtHint'></div>
<div id='txtIhnt'></div>
<div id='txt'></div>
If I put an int on the query of the last table, change the $h for a 13, it works, or if I change the ajax function on > xmlhttp.open("GET","ajax.php?h=13",true); it works too.
I think your problem is coming from this line here
if(str=""){
Rather that doing a comparison you are assigned an empty string to the str variable. So from that point on in the function the value of str will be "". You want to change it to
if(str==""){

Javascript/PHP redirect

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!

Categories