Hi I have a page that displays all of the contents of my table. Alongisde each row of the table I also have a column containing a checkbox. When the user selects one or more rows by ticking the checkbox and pressing the submit button, I want just those rows to appear in a table on the next page (buy.php). I know it is basically a select statement per row that is selected. But I dont know how to approach this. Can anybody help? Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping</title>
</head>
<body>
<form action='buy.php' method='post'>
<input type='submit' value='Submit' />
</form>
<h1>Buy</h1>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items';
if ($r = mysql_query($query, $db)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
<td><input type='checkbox' name='buy[{$row['ID']}] value='buy' /></td>
</tr>";
}
print "</table>
</form>";
} else {
print '<p style="color: blue">Error!</p>';
}
mysql_close($db); // Close the connection.
?>
</body>
</html>
EDIT: I tried the suggestion below and I did not get a table. Just the title of the page appeard:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Confirmation</title>
</head>
<body>
<h1>Order Details</h1>
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
foreach($_POST['buy'] as $item) {
$query = 'SELECT * FROM Items WHERE ID = $item';
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
} else {
print '<p style="color: blue">Error!</p>';
}
}
mysql_close($db);
?>
</body>
</html>
You need to create a dynamic SQL query.
1) I suggest you change your checkbox to the following
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
2) Loop through all of the buy options
<?php
foreach($_POST['buy'] as $item) {
// Append the ID (in the $item variable) to the SQL query, using WHERE `ID` = $item OR `ID` = $item and so on
}
?>
UPDATE:
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items WHERE ';
$item_count = count($_POST['buy']);
for($i = 0; $i < $item_count; $i++) {
$itemid = (int)mysql_real_escape_string($_POST['buy'][i]); // Secures It
$query .= '`ID` = '.$itemid;
if($i +1 < $item_count) {
$query .= ' OR ';
}
}
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
mysql_close($db);
?>
// this checkbox use
//buy.php foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item"; //use " "
// try it if any problem please carefully look you database table // download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
// this checkbox use
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
//buy.php
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item";
//use " "
// try it if any problem please carefully look you database table
// download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
Related
I am working on an assignment, and it requires me to select a "slip_id" from the 3aStudent_Slip.php and pass it to 4aservice_request.php and populate a table that is being built in the php code. I have NOT had any php classes so I am really struggling with why it's NOT getting any database from the "ProgrammingDatabase" on the server.
Using the following code ...
<?php
require_once('auth.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Service Requests</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="innerWrapper">
<h1>Service request by <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
Login Page |
Menu Page |
Logout
<?php
$slip_id = strtoupper($_POST['slip_id']);
echo("<h2>Services for Slip ID $slip_id</h2>");
//Verify Password
$vlogin=$_SESSION['vlogin'];
$vpassword=$_SESSION['vpasswd'];
//Connection String
$con=mysql_connect("localhost", $vlogin, $vpasswd);
if(!$con)
{
die("Could not connect".mysql_error());
}
//Select Database
mysql_select_db("ProgrammingDatabase", $con);
//The actual SQL code goes below into the structured variable $result
$result=mysql_query("SELECT * FROM service_request");
//Constructing the table and column names
echo "<table border='1'>
<tr>
<th>Service ID</th>
<th>Description</th>
</tr>";
//Looping until there are no more records from $result
//If there are records, print the column for that row
//do the while loop below with the variables from $result
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['service_id']."</td>";
echo "<td>".$row['description']."</td>";
echo "</tr>";
}
echo "</table>";
//Close the SQL connection string
mysql_close($con);
?>
<br />
<form action="a4Services_Student.php " method="post">
<br />
</form>
</div>
</body>
</html>
As some of the comments have already stated, the function you are using is not safe and is also depreciated.
The best way is to use PDO.
I have an example of it here https://snippetbox.xyz/5c3db100112bca204643/
<?php
/** How to get information out a database securely **/
$id = 6; // example value
//connect to mysql database using pdo
$conn = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password);
$query = "SELECT * FROM myTable WHERE id = :id";
//prepare the statement to avoid sql injection
$stmt = $conn->prepare($query);
//load variable into the statement and execute
$stmt->execute(array('id' => $id));
//fetch the results
$rows = $stmt->fetchAll(PDO::FETCH_OBJ);
//loop through all the lines
foreach ($rows as $row){
//loop through results here
//example
//echo $row->value;
}
?>
I want to insert an image into a selected category in the drop down menu. Didn't want to hard code the menu in html so it can be dynamically updated by phpmyadmin to menu. Currently, all images insert in Greeting_Cards table because it is a place holder for now.
I have tried saving it as a variable: $selected = $_POST['tables']; and passing it as $selected rather than greeting_cards, but that throws back a notice of undefined index and doesn't add to any table at all.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>upload</title>
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit" name="submit" value="upload" />
</form>
<?php
require_once('/var/db_file.php');
//To do after submit button
if(isset($_POST['submit']))
{
mysql_connect("localhost","root", $pass);
mysql_select_db("images");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
/* Drop down menu */
$dbname = "images";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
$tableNames=array();
while($row = mysql_fetch_row($result)){
$tableNames[] = $row[0];
}
echo '<select name="tables" id="tables">';
foreach($tableNames as $name){
echo '<option value="' . $name . '">' . $name . '</option>';
}
echo '</select>';
/* Drop down menu end */
$selected = $_POST['tables'];
echo '<br>';
if(substr($imageType,0,5) == "image"){
mysql_query("INSERT INTO `$selected` VALUES('','$imageName','$imageData')");
echo "Image Uploaded!";
}
else{
echo "Has to be an image!";
}
}
?>
</body>
</html>
Edit 1: Added the $selected variable in, instead of Greeting_Cards
Fix: Moved ending tag of form to encompass the php code.
Thanks for your help!
In this code snippet, the $_POST['tables'] is not getting the assigned value, as the form does not have the select dropdown named tables.
Despite the dropdown is being echoed, it is outside the <form>, thus not being submitted.
i have a website i am constructing for a school project, in which i already have various webpages where i get tabular data from my database through the use of While and Foreach.
But on this page in question, i am attempting to retrieve data from various tables, in order for a user to choose a category, and a text and submit.
But for some reason it isn't outputting any data. If i attempt with only one table and without using the table.field method, and only typing the fields, it works.
But from what i know, to retrieve from various tables i have to do so.
Can annione help me out on this?
<html>
<head>
<script type="text/javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$query = "SELECT texto.titulo,texto.ID,categoria.categoria,categoria.id FROM categoria,texto";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo "<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>'";
echo "<button type='submit'>Submeter</button>";
echo "<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>";
echo "<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if ($campo == "texto.titulo") {
echo "<tr><td>'".$valor."'</td>";
}
if ($campo == "texto.ID") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
if ($campo == "categoria.categoria") {
echo "<td>'".$valor."'</td>";
}
if ($campo=="categoria.id") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
}
}
echo "</form>";
echo "</table>";
echo "</center>";
?>
</body>
</html>
Added: Since both tables have a field called id, it won't let me simply put the field names, i have to also put the table name like i did. And yes, i have verified and both tables are populated with data, they work fine on other pages.
This is what I suggest (I didn't consider much code optimization).
<?php
$data = array();
mysql_connect('localhost', 'root', '') or die('problema na conexao');
mysql_select_db('trabalho1');
// Use the same field-names/aliases: id, info
$query = 'SELECT ID AS id, titulo AS info FROM texto';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
// Use the same field-names/aliases: id, info
$query = 'SELECT id, categoria AS info FROM categoria';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
?>
<html>
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<center>
<table border='2'>
<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>
<tr><td colspan ='2'><button type='submit'>Submeter</button></td></tr>
<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>
<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>
<?php
foreach ($data as $row) {
echo '<td><input type="radio" name="nome" value="' . $row['id'] . '></td></tr>' .
'<tr><td>' . $row['id'] . '</td>';
}
?>
</form>
</table>
</center>
</body>
</html>
PS: Read about my response about double quotations. Should I use curly brackets or concatenate variables within strings?
I am just building a simple search page in PHP. I need to know how can i keep the selecte value of the drop down list upon form submission. Currently, the value resets to the first index.
Can I do this via PHP without using client-side script?
Here is the code:
<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method="get">
<select name="field" id="field">
<?php
/*if($field == 'Active')
'selected="selected"';
*/
while($rows = mysql_fetch_array($result))
echo '<option>'.$rows['customer_id'].'</option><br>';
?>
</select>
<?php
if (isset($_GET['Search']) && $_GET['action']=='search')
{
$sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo '<br>Customer Name: '.$row['customer_name'].'<br>';
echo 'Email Address: '.$row['Email_Addr'].'<br>';
echo 'Contact No: '.$row['Contact_No'].'<br>';
}
?>
<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>
usually like this.
echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';
And please don't use the mysql_* functions to write new code, especially when you are learning. The mysql_* functions are in the process of becoming deprecated, they will be removed in future versions of PHP. Use mysqli_* or PDO objects instead.
You can check if the get value is the same than the select value :
while($rows = mysql_fetch_array($result))
echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';
When printing the select options, you can check for the value and set any mathing option to selected, maybe like this:
while($rows = mysql_fetch_array($result)){
if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
}
else {
echo '<option>'.$rows['customer_id'].'</option><br>';
}
}
I have 3 files
1) show_createtable.html
2) do_showfielddef.php
3) do_showtble.php
1) First file is for creating a new table for a data base, it is a fom with 2 inputs, Table Name and Number of Fields. THIS WORKS FINE!
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1>Step 1: Name and Number</h1>
<form method="post" action="do_showfielddef.php" />
<p><strong>Table Name:</strong><br />
<input type="text" name="table_name" size="30" /></p>
<p><strong>Number of fields:</strong><br />
<input type="text" name="num_fields" size="30" /></p>
<p><input type="submit" name="submit" value="go to step2" /></p>
</form>
</body>
</html>
2) this script validates fields and createa another form to enter all the table rows.
This for also WORKS FINE!
<?php
//validate important input
if ((!$_POST[table_name]) || (!$_POST[num_fields])) {
header( "location: show_createtable.html");
exit;
}
//begin creating form for display
$form_block = "
<form action=\"do_createtable.php\" method=\"post\">
<input name=\"table_name\" type=\"hidden\" value=\"$_POST[table_name]\">
<table cellspacing=\"5\" cellpadding=\"5\">
<tr>
<th>Field Name</th><th>Field Type</th><th>Table Length</th>
</tr>";
//count from 0 until you reach the number fo fields
for ($i = 0; $i <$_POST[num_fields]; $i++) {
$form_block .="
<tr>
<td align=center><input type=\"texr\" name=\"field name[]\"
size=\"30\"></td>
<td align=center>
<select name=\"field_type[]\">
<option value=\"char\">char</option>
<option value=\"date\">date</option>
<option value=\"float\">float</option>
<option value=\"int\">int</option>
<option value=\"text\">text</option>
<option value=\"varchar\">varchar</option>
</select>
</td>
<td align=center><input type=\"text\" name=\"field_length[]\" size=\"5\">
</td>
</tr>";
}
//finish up the form
$form_block .= "
<tr>
<td align=center colspan=3><input type =\"submit\" value=\"create table\">
</td>
</tr>
</table>
</form>";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create a database table: Step 2</title>
</head>
<body>
<h1>defnie fields for <? echo "$_POST[table_name]"; ?>
</h1>
<? echo "$form_block"; ?>
</body>
</html>
Problem is here
3) this form creates the tables and enteres them into the database.
I am getting an error on line 37 "Parse error: syntax error, unexpected $end in /home/admin/domains/domaina.com.au/public_html/do_createtable.php on line 37"
<?
$db_name = "testDB";
$connection = #mysql_connect("localhost", "admin_user", "pass")
or die(mysql_error());
$db = #mysql_select_db($db_name, $connection)
or die(mysql_error());
$sql = "CREATE TABLE $_POST[table_name](";
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[field_length][$i] !="") {
$sql .=" (".$_POST[field_length][$i]."),";
} else {
$sql .=",";
}
$sql = substr($sql, 0, -1);
$sql .= ")";
$result = mysql_query($sql, $connection) or die(mysql_error());
if ($result) {
$msg = "<p>" .$_POST[table_name]." has been created!</p>";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create A Database Table: Step 3</title>
</head>
<body>
<h1>Adding table to <? echo "$db_name"; ?>...</h1>
<? echo "$msg"; ?>
</body>
</html>
$result = mysql_query($sql, $connection) or die(mysql_error());
if ($result) {
$msg = "<p>" .$_POST[table_name]." has been created!</p>";
}
you missing a } in your last if statement, and your for loop is missing a } too
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[field_length][$i] !="") {
$sql .=" (".$_POST[field_length][$i]."),";
} else {
$sql .=",";
}
}
This error message means that a control structure block isn’t closed properly. In your case the closing } of some of your control structures like the for loop or the last if are missing.
You should use proper indentation and an editor that highlights bracket pairs to have a visual aid to avoid such errors.
You must close the for expression block:
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
// ...
}
Your for loop is not terminated. You are missing a }
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
}
And as pointed by others there is also a missing } for the last if statement:
if ($result) {
$msg = "< p>" .$_POST[table_name]." has been created!< /p>";
}
in your php.ini (php configuration) change :
short_open_tag = Off
you opened php tag shortly at line 1
just find and replace all <? with <?php
Stylistic tip: Use HEREDOCs to assign blocks of text to a variable, instead of the hideous multi-line-with-tons-of-escaping-backslashes constructs you're using. They're far easier to read and less error prone if/when you happen to forget a \ somewhere and break the script with a parse error.
I just solved this error, after checking my code, I had no open tags/braces.
For me, I got this error when moving to a amazon server.
It turns out I needed to enable short_open_tag = On in my php.ini.
This solved this error for me.