I'm having a few problems with my "architecture". I'm really rusty in this field.
So the code below is basically PHP that reads a database table and prints row by row (columns are "name" (text), and "votes" (int) ) with a button near each row which is named by the "name" column as in the table.
Very simple by now, works perfectly.
Now, each button should add +1 to a row in table in the database (to votes column), by the name of the button, simple, but since the number of buttons is not constant and is changing by the number of rows in each table (dynamic), I need to create a JS event that will get a button pressed with its name/value, and call a php function (I need specifically with functions) with the name as a variable (parameter), so it will add +1 to the votes where the name is the name pressed).
$allsql = "SELECT * FROM `voting` ORDER BY `voting`.`groupName` DESC, `voting`.`votes` DESC";
$result = mysqli_query($conn, $allsql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="post" id="voting_area">';// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$votes = $row["votes"];
echo 'name: ' .$name. ' - votes: ' .$votes. ' <button type="button" name="'.$name.'" value="'.$name.'">'.$name.'</button><br>';
}
echo '</form>';
}
Please try and explain me specifically each code (JS, AJAX, PHP).
Related
I need to disable or hide, button if existsusername in the table, and == logged in user
For example: username John exists in table paym we should disable button to John
table: paym
ID username column1 column2
+-------+-------------+-------------+-----------+
| 1 | John | Value | Value |
+-------+-------------+-------------+-----------+
| 2 | Alex | Null | Null |
+-------+-------------+-------------+-----------+
Only infrmation that I can provide you:((
This is button in Html:
<input class="reload-but" type="button" value="↻"">
** logic behind similar to this php code:**
<?php
$user_check_query = "SELECT * FROM paym
WHERE username = '" . $_SESSION['username'] . "' ";
$result = mysqli_query($db, $user_check_query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
?>
Who can do fully workable code, with explained code!
Related topic to this!!
1 method is that you can populate the table in Php by echoing the Table in HTML.
Another method would be to use a for loop in ur html looping through your data and do an if else in the loop to check the existence of the username. If true, use this set of button codes, if false, use this set of button codes.
The code snippet is a little bit out of context, so it's hard to know if this is possible, but assuming your PHP and HTML are part of the same script file (or least the one with the HTML includes/requires the one with the database code), then you can do something simple like this:
<?php
$user_check_query = "SELECT * FROM paym WHERE username = '" . $_SESSION['username'] . "' ";
$result = mysqli_query($db, $user_check_query);
$showButton = (mysqli_num_rows ($result) > 0 ? true : false);
?>
...
<?php
if ($showButton == true) {
?>
<input class="reload-but" type="button" value="↻"">
<?php
}
?>
This will cause PHP to only send the button HTML to the browser when the if condition is true.
echo "<input class=\"reload-but\" type=\"button\" value=\"↻\"".(count($row) > 0 ? " disabled" : " ".">";
Or, as #Justinas said, you can just echo the button only when you have a positive result.
I have a database with 100 rows. I have a button that shuffle those id's and print out 3 random ids.
HTML
<form method="post">
<button>Shuffle</button>
</form>
PHP
$sql = "SELECT id, description FROM fantasies_original ORDER BY RAND ( ) LIMIT 3";
$res = $mysqli->query($sql);
//print($res);
if ($res->num_rows > 0) {
// output data of each row
while($row = $res->fetch_assoc()) {
echo "Store Number: " . $row["id"]. "<br>" .
"Description: " . $row["description"]. "<br><br>";
}
} else {
echo "0 results";
}
I would like to visualize the counter. So when I press the button I can see the number of the id there is loop through in the database. I have been looking everywhere to find a library that could do the job.
Does anybody knows a library or have a suggestion how to do that?
I have two dropdowns in my form.
1)Brand Name of car
2)Model name in which data is going to be retrieved from database on the basis of brand name selected.
so I have taken a div tag and appended that second dropdown.The data in dropdown is displayed properly but the problem is in storing the data selected from the second dropdown, It stores the model name upto the space only.length in the database for that field is also taken properly.
eg- if the model name is "series 1" than it will store only series.
Php page of second dropdown:
<?php
$brand = $_GET['brand'];
include('connection.php');
$sql = "select * from modelname where Brand_Name='" . $brand . "'";
$result = mysqli_query($conn, $sql);
$html = "";
$html = '<select name="model">';
while ($row = mysqli_fetch_assoc($result)) {
$html.='<option value=' . $row['M_Name'] . '>' . $row['M_Name'] . '</option>';
}
$html.='</select>';
echo $html;
?>
because you are not quoting your attributes.
value=hello world
is seen as
value="hello" world
Add the missing quotes.
I'm building a web App for a friend, this is my first async site and I'm learning lots of cool stuff, but there are some details that make me struggle.
This is the general idea:
This simple app gets specific tables from a database using PHP and jQuery and shows them asynchronously on the page. There's this specific table (a waitlist) that shows all atributes from all entries on the table plus a small button that SHOULD delete that specific entry, the PHP code for the creation of the table is as follows:
<?php
include("con.php");
$result = mysqli_query($c,"SELECT * FROM waitlist");
echo "<thead>";
echo "<tr>";
echo "<th>Nombre</th><th>Sillas</th><th>Hora de Llegada</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID'] . ' id="deleteWaitlist">X</button>
</td>';
echo "</tr>";
}
echo "</tbody>";
mysqli_free_result($result);
?>
This is the table schema:
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL,
PRIMARY KEY(ID)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
What is the best way of having the button delete the entry it apears on? The function refreshes the table every few seconds so deleting it from the database is all I need. I also have an incomplete PHP function that gets called on buttonpress that shold delete the entry, but Im unsure as to how to complete it. Here it is:
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
I need to replace the $_POST[name] with an identifier for the row, this is my problem. What's the best way of doing this? Can I pass it somehow though the jquery.ajax() call? Do I need a new table attribute ID? I'm sure the "this" keyword can be used somewhere. Is PHP and ajax even the best way of doing it?
Ajax writes the table on "#result_table", here's the relevant code if it's needed:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
</div>
EDIT: I updated the code as recomended by #vnponce
This is the code for the ajax call:
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
console.log(result);
}
});
});
After fiddling with the code I got rid of all errors and updated the post, but the entries are still not getting deleted.
The best way is creating an ID identifier in your table, then this identifier can be added in your 'Delete' button.
The button trigger a function that send ID, and your PHP file recive it and delete de data comparing the ID.
The identifier can be added in table schema ( i don't know if it is the rigth code, I always made in phpMyAdmin )
CREATE TABLE WAITLIST (
ID MEDIUMINT NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255),
CHAIRS VARCHAR(255),
CREATED DATETIME NOT NULL
);
First add the ID in delete photo.
echo '<td>
<button class="btn btn-default" type="submit" name=' . $places ['ID']. ' "id="deleteWaitlist">X</button>
</td>';
The ajax
$("#deleteWaitlist").click(function(){
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({url: "YOUR_PHP_FILE.php", {id: i}, success: function(result){
// do some code here
// here yo can see 'result' response of YOUR_PHP_FILE
// console.log(result);
}});
});
Now your PHP with ID
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
mysqli_query($c,$sql);
?>
Well I hope help. If i have an error or you have a question let me know.
UPDATE*
Maybe there's an error deleteWaitlist.php , you can return error if it exist.
<?php
include("con.php");
$sql = "DELETE FROM waitlist WHERE id='.$_POST[id]'.";
if ( ! mysqli_query($c,$sql) )
{
return "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
I have a scenario like this:
I will take a number as input and will store in the database along with other information. And will display the data from the database as per the number position that have been taken as input. For example: if the input is 4, the display order will be in fourth position.
I want to make this using PHP/Mysql.
Thanks for the suggestions...
suppose you have field serial_number in your table iserted for serial by input, then firstlly you have to fetch table in array and then sort the table according to the serial number the code is like follow
<?php
$con=mysql_connect("localhost","root","");
$sql="select * from sort.data";
$result=mysql_query($sql,$con);
$data=array();
while($row=mysql_fetch_assoc($result))
{
$data[]=$row;
}
echo '<br />content of data before sorting';
echo '<pre>';
print_r($data);
echo '</pre>';
$final = array();
foreach($data as $key=>$item)
{
for($i=0;$i<$key;$i++)
{
if($data[$i]['serial_number']>$data[$key]['serial_number'])
{
$temp = $data[$key];
$data[$key] = $data[$i];
$data[$i] = $temp;
}
}
}
echo '<br />content of data after sorting';
echo '<pre>';
print_r($data);
echo '</pre>';
?>
here lastly $data containing the sorted array as per your requirement then you applay the table and td on it for formatting
as Saurabh Sinha commented. I am describing his comment.
store your input value in table such as position
$position = $_REQUEST['position']; // position submit by your form eg:4
insert record with position
mysql_query("INSERT INTO `your_table`(field1, field2,....,position) VALUES('$field1_value', '$field2_value',.....,'$position')");
now when ever you retrive your records and be sort according to the position. using ORDER BY like this
$sql = "SELECT * FROM `your_table` WHERE [YOUR CONDITIONS] ORDER BY position [DESC/ASC]";
in [] optional.
eg : if you have no condition to apply and want to order in Descending use given query
$sql = "SELECT * FROM `your_table` ORDER BY position DESC";