MSSQL and PHP: Select specific row based on which button is clicked - php

I am making a website for a mock book database using MSSQL where users can search for different books and select particular books that they might like to add to a list of favorites under their account name. The problem I am having is that I have no idea how to differentiate which book selection they want to add to their favorites because I can't figure out how to set the ISBN of the book, which uniquely identifies it, to a php session variable. If anyone can shed some light on this I would appreciate it, have been trying to figure it out all day.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
//Search to run if searching for book title
if(isset($_GET['searchBook'])){
$searchBook = $_GET['searchBook'];
$query = "SELECT BOOK.ISBN, Title, Author, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Title LIKE '%$searchBook%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Search to run is searching for a book author
if(isset($_GET['searchAuthor'])){
$searchAuthor = $_GET['searchAuthor'];
$query = "SELECT BOOK.ISBN, Title, Author, Genre, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Author LIKE '%$searchAuthor%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Store query result
$query_result = mssql_query($query, $connection)
or die( "ERROR: Query is wrong");
//Set up table to display search results
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><input name=\"".$line['index']."\" type=\"submit\" value=\"Add To Favorites\"></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Not sure if this is relevant but the following code is my best attempt at getting the value of ISBN that corresponds to the row of the button being clicked, which doesn't exactly work like I had hope.
//Get the ISBN
$data = mssql_fetch_assoc($query_result);
$ISBN = $data['ISBN'];
echo $ISBN;
Here is the code for my addFavorite.php which is where the form action is set to. This is the file that needs to know what user is adding a book as a favorite AND what book they are adding to that list.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
$User = $_SESSION['userID'];
//Set up query
$query = "INSERT INTO FAVORITES VALUES(\"$User\",\"**I NEED A SESSION VARIABLE OR SOMETHING TO GO HERE\")";
//Store query result
$query_result = mssql_query($query, $connection)
//or die( "ERROR: Query is wrong");
Any help would be much appreciated. I know it's alot of information and if there is anything that doesn't make sense or I have forgotten to provide please let me know. Thanks.
EDIT
I have tried using the BUTTON instead of using INPUT but the value of the button is not setting to anything for some reason.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records **PROBLEM IN HERE since $line['ISBN'] returns nothing**
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line['ISBN']."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
EDIT 2
Finally got it working, thanks to everyone for helping! Partial code that was problematic posted below in working condition.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line[0]."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";

Use a BUTTON-element instead of the INPUT-element. That way, you can use the 'value'-attribute of this element to pass the correct value.
echo "<td><button name=\"$line['index']\" value=\"$line['ISBN']\" type=\"submit\">Add to favorites</button></td>";
Although I would suggest using AJAX instead of the above approach for this: use the onclick event from a button to execute javascript that calls a seperate php-file and passes the correct ISBN-number. This is then added to the database and your original page should be refreshed or part of the page reloaded.

Related

Get the values of the ticked checkboxes in php

I am currently building a web application. In my application, a load some data from mysql and I display them as a table in my website. Additionally I add another column that consists of different checkboxes. My source code of displaying the table is called by a function that is located in another page. The source code odf the function is the following :
function user_clients_table() {
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table border=2>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Receive Message</th>
</tr>";
while($record = mysql_fetch_array($clients)){
echo "<form action=pushnotification.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<input type=checkbox name=checkbox[] value=".$record['ID']." />". "</td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
mysql_close();
}
The function works fine, after i call the function my webpage looks like this:
I want next to display the client number whose check box has been checked after i click the button send. For example if i checked only the first check box and submit it, i want to echo the client id that matches thsi checkbox, in this case i will echo '2'. My approach to this is the following:
if(isset($_POST['send'])){
if(!empty($_POST['checkbox'])) {
// Counting number of checked checkboxes.
$checked_count = count($_POST['checkbox']);
echo "You have selected following ".$checked_count." option(s): <br/>";
// Loop to store and display values of individual checked checkbox.
foreach($_POST['checkbox'] as $selected) {
echo "<p>".$selected ."</p>";
}
echo "<br/><b>Note :</b> <span>Similarily, You Can Also Perform CRUD Operations using These Selected Values.</span>";
}
else{
echo "<b>Please Select Atleast One Option.</b>";
}
}
It works but only for the first checkbox, if I select the other checkboxes without the first one I doesn't display anything.
Can someone please help me?
Thanks in Regards
Each checkbox is in it's own form, so when you are submitting you are submitting the first form (the first checkbox), and that is why you are getting the current action. Put the form tags outside the loop

PHP MySQL save a row id to a database based on user checkbox

I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>

php fetch column values from database and display in html table column

I have a table in database name Accounts in which i have many rows and many columns, i want to show a column Account (all values) in my html table. I have tried many method to show a specific column values without using index in html using php and I am using MySql.
$storeArray = Array();
while($rowval = mysql_fetch_array($whole, MYSQL_ASSOC))
{
$storeArray[] = $rowval['Account'];
$status= $rowval['status'];
$ph1= $rowval['Phone1'];
$ph2= $rowval['Phone2'];
}
by using <?php echo $storeArray[0]; ?> and <?php echo $storeArray[1]; ?> in <td> i got the solution. My question is there any way, it automatically show all values without providing any index?
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select username from User");
echo "<table border='1'>";
echo "<tr><th>Username</th></tr>";
while(list($username)=$rows->fetch_row()){
echo "<tr><td>$username</td></tr>";
}
echo "</table>";
This is a pretty elaborate question. I think the best I can do is point you in the right direction. There is a good tutorial for this on w3schools.com. You should at least read these:
PHP - Connect to MySQL
PHP - Select Data From MySQL
and maybe
PHP - Limit Data Selections From MySQL
**file user.php**
<?php
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select id,username from User");
echo "<table border='1'>";
echo "<tr><th>Username</th></tr>";
while(list($id,$username)=$rows->fetch_row()){
echo "<tr>";
echo "<td>";
echo "<form action='user_details.php' target='_blank' method='post'>";
echo "<input type='hidden' name='txtId' value='$id' />";
echo "$id - $username";
echo "<input type='submit' name='btnView' value='View' />";
echo "</form>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
**file user_details.php**
<?php
if(isset($_POST["btnView"])){
$id=$_POST["txtId"];
$conn=new mysqli("localhost","root","","your_db");
$row=$conn->query("select id,username,email,phone from User where id='$id'");
list($id,$username,$email,$phone)=$row->fetch_row();
echo $id," ",$username," ",$email," ",$phone;
}
?>
if you want to fetch more than one database column in your html table column.
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select col1,col2 from Tablename");
echo "<table border='1'>";
echo "<tr><th>col1</th><th>col2</th></tr>";
while(list($col1, $col2)=$rows->fetch_row())
{
echo "<tr><td>$col1</td><td>$col2</tr>";
}
echo "</table>";

Get line breaks in the my-sql_fetch_array table results

I have a simple project that I am working on and I'm having a hard time finding the code I need to get line breaks in the following table:
<?php
// connect to the database
$host = '###';
$username = '###';
$pass = '####';
mysql_connect($host,$username,$pass) or die(mysql_error());
mysql_select_db("####") or die(mysql_error());
// select everything from the table
$query = "SELECT * FROM Employees";
$result = mysql_query($query) or die(mysql_error());
echo "<table>";
echo "<tr>";
while( ($row = mysql_fetch_array($result)))
{
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
}
echo "</tr>";
echo "</table>";
// disconnect from the database
mysql_close();
?>
Everything works correctly and it grabs data from the correct database and table. But when it displays results it is all on the same line ("record1record2record3") and I'd like a line break between employee records.
I've searched this question and it seems like my results all show me an entirely different way of doing this. I've already got the code written and fussed with it a lot to get it working. Can I just make a simple alteration to the above code to get the breaks I want?
The <tr> tags must also be inside the while loop so that they are outputted for each row. They make the rows in the HTML table.
while( ($row = mysql_fetch_array($result)))
{
echo "<tr>";
echo "<td>".$row['employeeid']."</td>";
echo "<td>".$row['firstname']."</td>";
echo "<td>".$row['lastname']."</td>";
echo "<td>".$row['department']."</td>";
echo "</tr>";
}

update MySQL resultset through user-interaction and make the changes global for the application

I fetching a result set from a MySQL table and displaying it on the web page as under:
<?php
$link = mysql_connect(....);
mysql_select_db(....);
$sql = "select * from products where category = '" .$_POST['prod_cat']. "'";
$rs = mysql_query($sql, $link);
echo "<form name='prodselect' action='prodlist.php' method='post'>";
echo "<table>";
$rowcount = 1;
while ($row = mysql_fetch_array($rs))
{
echo "<tr>";
echo "<td>" .$row['product_name']. "</td>";
echo "<td><input type='checkbox' name='line_" .$rowcount. "'></td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
?>
This displays the list of products with checkbox for every product row.
The user will select products using the checkboxes.
I want to display / save the selected products in the "Products for Purchase" list on another web page.
Please help me out.
Thanks.
I can suggest you to create the checkbox like this:
echo "<td><input type='checkbox' name='products[]' value='" .$row['product_id']. "'></td>";
then on the prodlist.php you can get the array $_POST['products']

Categories