I'm extracting data from a database with a SELECT statement.
I would like to put this data into something, which you can write in (and later put a button save, which uses a SQL statement to rewrite the rows data).
The current code is:
index.php with login logic
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="logik.php" method="POST">
Username: <input type="text" name="uname" />
Password: <input type="password" name="pwd" />
DB-Name: <input type="text" name="dbname" value="unternehmendb" />
<input type="submit" />
</body>
</html>
After the login the SQL logic:
logik.php
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="grafik.css">
<title>unternehmendb</title>
</head>
<body>
<h1>Mitarbeiter</h1>
</body>
</html>
<?php
//test2
$servername = "localhost";
$username = $_POST['uname'];
$pass = $_POST['pwd'];
$dbname = $_POST['dbname'];
// Create connection
$link = new mysqli($servername, $username, $pass, $dbname);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "<table>";
$sql = "SELECT * FROM mitarbeiter";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Vorname"]. "</td><td> " . $row["Strasse"]. "</td><td>" . $row["Position"] . "</td><td>" . $row["id"] . " </td></tr> ";
}
} else {
echo "0 results";
}
echo "</table>";
mysqli_close($link);
?>
You're on track but instead of echoing result in td only, you can add text input fields making the values for the name attribute an array since you're getting multiple rows.
Everything within this
if($result->num_rows > 0)
block should be changed to:
if ($result->num_rows > 0)
{
//output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr>
<td><input type='text' name='Name[]' value='".$row['Name']."' />
</td>
<td><input type='text' name='Vorname[]'
value='".$row['Vorname']."' /> </td>
<td><input type='text' name='Strasse[]'
value='".$row['Strasse']."' /> </td>
<td><input type='text' name='Position[]' value='".
$row['Position']."' /> </td>
<td><input type='text' name='id[]' value='".$row['id']."' />
</td>
</tr> ";
} //while()
?>
<tr> <td colspan="5"><center> <input type="submit" value="Save Data" />
</center></td></tr>
<?php
}// if result rows > 0
?>
Notice that after the loop, we created an additional row to house the
submit button.
Assuming there are no records, you could surround your statement in the else with since it will be printed within the tag as in:
echo "<tr> <td colspan='5'> No results Found </td> </tr>";
Hope this helps.
Related
I am trying to update my database using a php file that has an html form in it.
When I hit 'update' in the url bar, the updated information is showing. But when I go back to my HTML page that shows me everything in my database, it still has the old information.
What am I not doing?
I know there are security issues, like not using a session, or sanitizing the data, or using my_sql in general. This is just for a school project. After the semester I will be closing the hosting account.
EDIT: I moved the "$id = $_GET['id'];" line above the update query so that "$id" would be defined before query. Updated code.
EDIT2: After following the comments about turning on errors and displaying them after the update query. It showed that the ID was not in fact being read back in. So I added a hidden input value for the ID to give back to the file after the submit button was it.
<?php
error_reporting(E_ALL & ~E_DEPRECATED);
ini_set('display_errors', 1);
$host = 'hose';
$user = 'user';
$pass = 'pass';
$database = 'database';
$table = 'table';
//connecting to server
$conn = mysql_pconnect($host,$user,$pass);
//opening to database
if (!($db = mysql_select_db($database))) {
echo "Could NOT connect to database.";
}
//gathering new data from update form
if (isset($_GET['submit'])) {
$title= $_GET['title'];
$year = $_GET['year'];
$director = $_GET['director'];
$genre = $_GET['genre'];
$runtime = $_GET['runtime'];
$id = $_GET['id'];
$query = mysql_query("UPDATE `collection`
SET `title`='$title', `year`='$year', `director`='$director', `genre`='$genre', `runtime`='$runtime'
WHERE `ID`='$id'");
}
//passing in ID number and running query
$id = $_GET['id'];
$query = "SELECT * FROM '$table' WHERE ID = '$id'";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
//getting row data for ID number
$row = mysql_fetch_array( $result );
?>
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="webpage.css">
<style type = "text/css">
table, th, td {
border: 0px solid black;
border-collapse: collapse;
}
table {
margin: auto;
width: 50%;
}
td {
padding: 5px;
}
img {
text-decoration: none;
}
</style>
</head>
<body class="subStyle">
<div class="topnav">
Home
Database
Insert
</div>
<form class='form' method='get'>
<table border=0>
<tr>
<th>Movie Title</th>
<th>Year Made</th>
<th>Director</th>
<th>Genre</th>
<th>Runtime(Minutes)</th>
</tr>
<tr>
<td><input type=text name="title" id="title" maxlength=100 size=50 value="<?php echo $row['title']; ?>"></td>
<td><input type=text name="year" id="year" maxlength=4 size=10 value="<?php echo $row['year']; ?>"></td>
<td><input type=text name="director" id="director" maxlength=100 size=30 value="<?php echo $row['director']; ?>"></td>
<td><input type=text name="genre" id="genre" maxlength=20 size=20 value="<?php echo $row['genre']; ?>"></td>
<td><input type=text name="runtime" id="runtime" maxlength=4 size=20 value="<?php echo $row['runtime']; ?>"></td>
<td><input type=hidden name="id" id="id" value="<?php echo $row['ID']; ?>"></td>
</tr>
<tr><td></td><td></td><td>
<button class='submit' type='submit' name='submit' value='update'>Update Movie</button></td></tr>
</table>
</form>
</body>
</html>
<?php
//check if update worked
if (isset($_GET['submit'])) {
echo '<div class="form" id="form3"><br><br><br><br><br><br>
<Span>Data Updated Successfuly</span></div>';
}
//close connection
mysql_close($conn);
?>
Your code is insecure - Why shouldn't I use mysql_* functions in PHP?
I think the issue is down to variables not being defined - in your query:
UPDATE '$table' SET `title`='$title', `year`='$year',
`director`='$director', `genre`='$genre', `runtime`='$runtime'
WHERE `ID`='$id'
$id is not defined
I'm trying to figure out how to use the text box and radio buttons to search for items in the database. Here's my code so far. I'm a php beginner. Also I'm kinda confused btw pdo and mysqli. I'm really stuck. Thanks
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>northwind database</title>
</head>
<body>
<?php
//connect databse
$dsn = 'mysql:host=localhost;dbname=northwind';
$username ='sa' ;//'mgs_user';
$password = '123';//'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo'<p>You are connected</p>';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
require_once ('index.php');
}
?>
<?php
//PDO:: query
/*function getFruit($conn) {
$sql = 'SELECT id, first_name, last_name FROM customers ORDER BY first_name';
foreach ($conn->query($sql) as $row) {
print $row['id'] . "\t";
print $row['first_name'] . "\t";
print $row['last_name'] . "\n";
}
}*/
$query="SELECT id,Company, first_name, last_name FROM customers";
$display = $db->prepare($query);
$display->execute();
$customer = $display->fetchAll();
$display->closeCursor();
?>
<h1> Customer List </h1>
<p>Search</p>
<form name="searchDatabase" method="post" action="Index,php">
<input name="search" type="text" size="40" maxlength="50" /><br />
<input name="RadioId" type="radio" value="Id" />ID<br />
<input name="RadioId" type="radio" value="Company" />Company<br />
<input name="RadioId" type="radio" value="FName" />First Name<br />
<input name="RadioId" type="radio" value="LName" />Last Name<br />
<input name="RadioId" type="radio" value="Title" />Title<br />
<input type="submit" name="Submit" size="10" value="Search" />
</form>
<br /><br />
<table>
<tr>
<th>ID</th>
<th>Company</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<?php foreach ($customer as $cus) :?>
<tr>
<td><?php echo $cus['id']; ?></td>
<td><?php echo $cus['Company']; ?></td>
<td><?php echo $cus['first_name']; ?></td>
<td><?php echo $cus['last_name']; ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
I'm struggling now for a few days to get the value of a checkbox in my code.
Basically I have an admin-page where the customer can select and deselect images that will put online.
You can select and deselect images that will be shown on the homepage, and separate on the gallery-page. Both checked is also possible.
I have another checkbox that can be selected to remove the image from the list(image_deleted).
There is still a database entry and the images are still on file-system but later on I'll create a cleanup-job.
Here is my code:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
ob_start();
require('../../lib/dbconnection.php');
require("../../lib/checklogin.php");
require("includes/upload.inc.php");
$query = 'SELECT * FROM gallery where image_deleted != 1 order by id desc';
$result=$conn->query($query);
$count=$result->num_rows;
?>
<!DOCTYPE html>
<html>
<head>
<title>Classic Nails - CMS</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="ClassicNails">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/screen.css">
<link rel="stylesheet" href="../css/libs/magnific-popup.css">
<script src="../js/libs/min/jquery-min.js" type="text/javascript"></script>
<script src="../js/min/custom-min.js" type="text/javascript"></script>
<script src="js/jquery.magnific-popup.js"></script>
<script>
$(document).ready(function() {
$('.image-link').magnificPopup({
type:'image',
gallery:{
enabled:true
}
});
});
</script>
</head>
<body>
<?php include('includes/header.inc.php'); ?>
<?php include('includes/nav.inc.php'); ?>
<div class="wrapper">
<article class="content">
<h1>Foto gallery</h1>
<?php
if (isset($uploadResult)) {
echo "<p><strong>$uploadResult</strong></p>";
}
?>
<form action="" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">
<p>
<label for="image">Upload image:</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<input type="file" name="images" id="imagesd" />
</p>
<p>
<input type="submit" name="upload" id="upload" value="Upload" />
</p>
</form>
<div id="maincontent">
<h2>Foto informatie</h2>
<form name="FotoInformatie" id="fotoInformatie" method="post" action="">
<table>
<tr>
<td align="center"><strong>Foto<strong></td>
<td align="center"><strong>Titel</strong></td>
<td align="center"><strong>Beschrijving</strong></td>
<td align="center"><strong>Homepage</strong></td>
</tr>
<?php
while ($rows=$result->fetch_assoc()) {
?>
<tr>
<td class="hide" align="center"><?php $id[]=$rows['id']; ?><?php echo $rows['id']; ?></td>
<td><img src="../img/thumbs/<?php echo $rows['filename']; ?>"></td>
<td align="center"><input name="title[]" type="text" id="title" value="<?php echo $rows['title']; ?>"></td>
<td align="center"><input name="caption[]" type="text" id="caption" value="<?php echo $rows['caption']; ?>"></td>
<td><input type="checkbox" name="checkboxHome[]" id="checkBoxHome" value="<?php echo ($rows['home'] == 1) ? 'checked="checked"' : ''; ?>"/></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center">
<input type="submit" name="submit" value="Submit">
</tr>
</table>
</form>
</div>
</article> <!-- end of content -->
</div> <!-- end of container -->
<?php include('includes/footer.inc.php'); ?>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$caption = $_POST['caption'];
if ($_POST['checkboxHome'] == "") {
$checkboxHome[] = '0';
} else {
$checkboxHome[] = '1';
}
for($i=0;$i<$count;$i++){
$result1=mysqli_query($conn, "UPDATE gallery SET title='$title[$i]', caption='$caption[$i]', home='$checkboxHome[$i]' WHERE id='$id[$i]'");
header("location:/admin/foto-admin.php");
}
}
?>
The checkbox only works on the first row in my DB. When I select another record, only the first record in my db will be updated.
Another issue is that my checkbox won't be checked so I don't know based on my screen when a image is online or not. in the database I see a 1 of a 0.
I know that sql-injection is possible and I have to prepare the statements, but that is the next step when I get this checkbox-issue working.
Hope someone can help me with my code. It's giving me a headache.
Check these
Attribute name="id[]" for id field is not given. And it should get inside
if(isset($_POST['submit'])) {
$id = $_POST['id'];
}
Incorrect spelling in getting Post value
change
$checkboxHome = $_POST['checkboxHome'];
$checkboxFotoboek= $_POST['checkboxFotoboek'];
$checkboxDelete = $_POST['image_deleted'];
to
$checkboxHome = $_POST['checkBoxHome'];
$checkboxFotoboek= $_POST['checkBoxFotoboek'];
$checkboxDelete = $_POST['checkboxDelete'];
You are trying to get wrong value.
Your check-box name is checkBoxHome and you are trying to get $_POST['checkboxHome'] instead of $_POST['checkBoxHome'] .
Try $_POST['checkBoxHome'] and print it as print_r('checkBoxHome')
Same mistake in checkBoxFotoboek check-box.
try this
if(isset($_POST['submit'])) {
$title = $_POST['title'];
$caption = $_POST['caption'];
$checkboxHome = $_POST['checkBoxHome'];
$checkboxFotoboek= $_POST['checkBoxFotoboek'];
$checkboxDelete = $_POST['checkboxDelete'];
for($i=0;$i<$count;$i++){
$result1=mysqli_query($conn, "UPDATE gallery SET title='$title[$i]', caption='$caption[$i]', home='$checkboxHome[$i]', fotoboek='$checkboxFotoboek[$i]', image_deleted='$checkboxDelete[$i]' WHERE id='$id[$i]'");
header("location:/admin/foto-admin.php");
}
}
?>
I'm trying to create a page which uses session data to find a user in a database and then sends the events that this user has signed up to. I'm a bit of a newbie and have got very confused with where I am at. I am using two different tables to get the data, and this is where I'm getting confused and where I believe the errors are occurring. Thanks in Advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<?php
$username = $_SESSION['username'];
$email = $_SESSION['user_email'];
$con=mysqli_connect("localhost","emuas","******","EMUAS_signUp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table>
<tr>
<td> Logged in as:</td>
</tr>
<tr>
<th>" . $username . "</th>
</tr>
<tr>
<td>
<form action='logout.php' method='post'>
<input type='submit' value='Logout' >
</form>
</td>
</tr>
<tr>
<th>Events Attending:</th>
</tr>";
$find = mysqli_query($con,"SELECT * FROM SIGN_UP_TEST WHERE User = '$username'");
while($find_row = mysqli_fetch_array($find)){
//Get Event ID
$eventId = $find_row['EventID'];
//Use Event ID to get Event Name
$result = mysqli_query($con,"SELECT * TEST WHERE EventID = '$eventId'");
//Insert Event Name into table with link from Page Name
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> <a href='http://www.emuas.co.uk/members/sign_up_sheets/S" . $row['PageName'] . ".php'>" . $row["EventName"] . "</a> </td>";
echo "</tr>";
}
}
echo "</table>";
?>
<body>
</body>
</html>
Warning this is lenghty! attack if you knowledagble. well at least more then a newb beginner like me.
This script uses three files as detailed below. It is suppoed to create the database and fields from the form input. It gets to the end and shows my_contacts has been created!. But when i go into phpMyadmin the table has not been created.
I have a file named show_createtable.html which is used to create a table in MySQL
<!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>
<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>
This Form Posts to do_showfielddef.php
<?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><th>Primary Key?</th><th>Auto-Increment?</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>
<td aligh=center><input type=\"checkbox\" name=\"primary[]\" value=\"Y\"></td>
<td aligh=center><input type=\"checkbox\" name=\"auto_increment[]\" value=\"Y\"></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>
Which in turn creates the table and fields with this file do_showfielddef.php
//connect to database
$connection = #mysql_connect("localhost", "user", "pass")
or die(mysql_error());
$db = #mysql_select_db($db_name, $connection)
or die(mysql_error());
//start creating the SQL statement
$sql = "CREATE TABLE $_POST[table_name](";
//continue the SQL statement for each new field
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[auto_increment][$i] =="Y") {
$additional = "NOT NULL auto_increment";
} else {
$additional = "";
}
if ($_POST[primary][$i] =="Y") {
$additional .= ", primary key (".$_POST[field_name][$i].")";
} else {
$additional = "";
}
if ($_POST[field_length][$i] !="") {
$sql .= " (".$_POST[field_length][$i].") $additional ,";
} else {
$sql .=" $additional ,";
}
}
//clean up the end of the string
$sql = substr($sql, 0, -1);
$sql .= ")";
//execute the query
$result = mysql_query($sql, $connection) or die(mysql_error());
//get a giid message for display upon success
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>
I cant believe I went to all the trouble of wrinting this Question. I had another good look at the phpMYAdmin and it had worked. The table had been created under a database called testDB which I assumed had nothing it in.
How did the script decided to etner this as a child under the testDB database?
Once again thanks everyone for your input, This site is truely amazine and is so valuable for a beginner like my self.