I am new to PHP and I made a simple program where you can apply your name and age, it will take the data to the database and the table will be added with a new row.
I want to add a new column where you can click "change", only the data from that particular row will show up in a few textboxes and can be changed. when pressing submit I want to use the UPDATE function to update the records.
example/plot:
Mike Towards 23 Change
Tyler Frankenstein 24
Change Sophie Baker 22
Change
I want to change the age of Sophie Baker to 24 so I press Change on that row.
Now I only want to get the data from that row and make some changes.
The code I have this far:
Drawing the table above the input fields and the input:
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="insert.php" method="post"><br />
<input type="text" name="firstname"> Firstname <br />
<input type="text" name="lastname"> Lastname <br />
<input type="text" name="age"> Age
<p><input type="submit"></p>
</form>
</body>
</html>
Parser:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
mysqli_close($con);
?>
I have tried a few things, but I cant figure out how to show the content on the row I want to select.
Change the actual data with the update function won't be the problem, so I only need help to get the actual data from the correct row.
you'd need to select with the primary key of that table if any exists. if not you should create one. I assume you have a primary key named PersonID:
$query = "SELECT * FROM Persons WHERE PersonID = '" . ($_GET['PersonID']) . "'";
to add the edit button:
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th><th>Action</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href = '?PersonID=" . $row['PersonID'] . "'>Edit</a></td>";
echo "</tr>";
}
echo "</table>";
I assume you have a column named "id".
you can do the following:
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// when you are in "edit mode" just display the row you will edit row
if (isset($_GET['id'])
$result = mysqli_query($con,"SELECT * FROM Persons where id = ".(int)$_GET['id']);
else
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='2'> <tr> <th>Voornaam</th> <th>Achternaam</th> <th>Leeftijd</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td><a href='?id=" . $row['id'] . "'>change</a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<html>
<body>
<br />
<form action="update.php" method="post"><br />
<input type="hidden" name="id" value="<?php echo isset($_GET['id']?$_GET['id']:'') ?>" />
<input type="text" name="firstname" value="<?php echo isset($row['FirstName'])?$row['FirstName']:'' ?>"/> Firstname <br />
<input type="text" name="lastname" value="<?php echo isset($row['LastName'])?$row['LastName']:'' ?>"/> Lastname <br />
<input type="text" name="age" value="<?php echo isset($row['Age'])?$row['Age']:'' ?>"/> Age
<p><input type="submit"></p>
</form>
</body>
</html>
update.php (handle both insertion and update):
<?php
$con = mysqli_connect("localhost", "user" , "", "personInfo");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['id'])
$sql="UPDATE Persons set FirstName = ?, LastName = ?, Age = ?
WHERE id = ".(int)$_POST['id'];
else
$sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES (?, ?, ?)";
$sth = mysqli_prepare($con, $sql);
$sth->bind_param($_POST[firstname],$_POST[lastname],$_POST[age]);
if (!$sth->execute())
{
die('Error: ' . mysqli_error($con));
}
echo "1 record ".(isset($_POST['id']?'modified':'added')." to the database";
echo "<p><a href=sql2.php>Back to form</a></p>";
Related
I've been trying to display the image I uploaded into the db using a simple insertform. I've only been able to retrieve the image-name into the "data-file", what I'm wondering is how can I easily display the image in the same form location instead of the image-name?
This is my result at this moment, as you can see I've only added an image to one of the inserts, and I would like to change the "footer.jpg-name" with the image displayed here.
<html>
<head>
</head>
<body>
<form action="insertform.php" method="post">
Topic: <input type="text" name="topic"><br />
Name: <input type="text" name="name"><br />
Attendance: <input type="text" name="attendance"><br />
Image: <input type="file" name="image"><br />
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])){
$con = mysql_connect("localhost","username","password");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("testingisfun",$con);
$sql = "INSERT INTO Lectures (Topic,Name,Attendance,Image) VALUES ('$_POST[topic]', '$_POST[name]', '$_POST[attendance]', '$_POST[image]')";
mysql_query($sql,$con);
mysql_close($con);
}
?>
</body>
</html>
Heres the "data-file".
<html>
<head>
</head>
<body>
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("testingisfun",$con);
$sql = "SELECT * FROM lectures";
$myData = mysql_query($sql,$con);
echo "<table border = 1>
<tr>
<th>Topic</th>
<th>Name</th>
<th>Attendance</th>
<th>Image</th>
</tr>";
while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['Topic'] . "</td>";
echo "<td>" . $record['Name'] . "</td>";
echo "<td>" . $record['Attendance'] . "</td>";
echo "<td>" . $record['Image'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Thanks for any sort of feedback!
Try this
echo "<td><img src='/{$record['Image']}'>" . $record['Image'] . "</td>";
I took this answer from linked answer that I had put in comments. There are other alternatives also provided for this problem.
echo "<td>" . $record['Image'] . "</td>";
replace with
echo "<td><img src=\"data:image/jpeg;base64,"" . base64_encode( $record['Image'] ) . "/></td>";
You are storing images in DB and while fetching it is giving you image data that is raw so to display images from data you can use this method.
This wont help in caching but it will solve the problem.
<?php
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if(!isset($_POST['submit'])){
$result = mysql_query("SELECT * FROM pleasework ORDER BY ID");
$row = mysql_fetch_array($result);
}
?>
<form action="?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
<img id="close1" src="X.png" width="25" height="25" onclick ="div_hide1()">
<h2><font size="6">Please change existing data</font></h2>
<hr>
<br>
<font color="yellow">Change Name to: </font><input type="text" name="New" value="<?php echo $row['Name'];?>"/><br><br>
<font color="yellow"> Change Cause to: </font> <input type="text" name="New1" value="<?php echo $row['Cause'];?>"/><br><br>
<font color="yellow">Change Symptom to: </font><input type="text" name="New2" value="<?php echo $row['Symptom'];?>"/><br><br>
<font color="yellow"> Change Gene_affected to: </font><input type="text" name="New3"value="<?php echo $row['Gene_affected'];?>" /><br><br>
<input type="hidden" name="id" value="<?php echo $_GET['ID'];?>"/>
<input type="submit" onclick="clicked(event)" />
</form>
<?php
if(isset($_POST['submit'])){
mysql_query("UPDATE pleasework SET Name= '$_POST[New]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Cause= '$_POST[New1]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Symptom= '$_POST[New2]' WHERE ID='$_POST[id]'");
mysql_query("UPDATE pleasework SET Gene_affected= '$_POST[New3]' WHERE ID='$_POST[id]'");
echo "Change Successful<br>" ;
header("Location: databse.php");
mysql_close($con);
}
else {}
?>
This is my php file.
while($row = mysql_fetch_array($result))
{
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . " </TD>";
echo "<TD>" . $row['Cause'] . " </TD>";
echo "<TD>" . $row['Symptom']. " </TD>";
echo "<TD>" . $row['Gene_affected'] . " </TD>";
echo "<TD><font color='red'>Delete row</font> </TD>";
echo "<TD><font color='red'>modify</font> </TD>";
echo "</TR>";
}
And this is the section which has a modify button that links to the edit.php file. The error here is that is doesnt bring over the values in the table to the editing page and then submitting the form doesnt work too. help please
Your code appears a bit confused.
First of all, why to put the modify routine after output the form? Especially since after modify you send the header function, that fails if previously there are some output.
Note also a typo: you forgot to properly open the php tag in the form declaration. Change-it in this way:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="form2" method="post" name="form2">
The main problem is that you check if the $_POST[submit] if set, but this is not set, due to the absence of attribute name.
Change it in this way:
<input type="submit" name="submit" onclick="clicked(event)" />
Now your script should work (I don't have tested the sql).
Please also note that your UPDATE routine is redundant: you can reduce the 4 statement to only one in this way:
$result = mysql_query
(
"UPDATE pleasework SET Name='{$_POST[New]}', Cause='{$_POST[New1]}', Symptom='{$_POST[New2]}', Gene_affected='{$_POST[New3]}' WHERE ID={$_POST[id]}"
);
About PHP Original MySQL API:
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0
NOTE: mysql_* deprecated, so try to use PDO or mysqli_*.
Simple way:
<?php
if(isset($_POST['submit'])){
$result = mysql_query("UPDATE pleasework
SET Name='".$_POST['New']."',
Cause='".$_POST['New1']."',
Symptom='".$_POST['New2']."',
Gene_affected='".$_POST['New3']."'
WHERE ID=".$_POST['id'].");
if($result ){
echo "Change Successful<br>" ;
header("Location: databse.php");
}
mysql_close($con);
}
YOUR PHP:
while($row = mysql_fetch_array($result))
{ $spaces = " ";
echo "<TR>";
echo "<TD>" . $row['ID'] ."</TD>";
echo "<TD>" . $row['Name'] . $spaces."</TD>";
echo "<TD>" . $row['Cause'] . $spaces."</TD>";
echo "<TD>" . $row['Symptom']. $spaces."</TD>";
echo "<TD>" . $row['Gene_affected'] . $spaces."</TD>";
echo "<TD><a href='delete.php?id=".$row['ID'] ."'>";
echo "<font color='red'>Delete row</font></a>".$spaces."</TD>";
echo "<TD><a href='edit.php?id=" . $row['ID'] ."'>";
echo "<font color='red'>modify</font></a>".$spaces."</TD>";
echo "</TR>";
}
I am using simple code to retrieve data from database table but not getting result it always shows "No Result found".
Table Structure
rollno Varchar(50) Primary Key,
name Varchar(100),
fname Varchar(100),
mname Varchar(100),
course Varchar(100),
duration Varchar(100),
address Varchar(100),
image blob.
HTML FORM CODE
<form name="input" action="q.php" target="display" method="post" >
Roll No: <input type="text" name="name">
<input type="submit" name="submit" value="Submit">
</form>
PHP CODE
<?php
if (isset($_POST['name'])) {
$con=mysqli_connect("mysql.1freehosting.com","u890130056_certi","samsungk2","u890130056_certi");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name = htmlspecialchars($_POST['rollno']);
{
$result = mysqli_query($con,"SELECT * FROM certificate where rollno ='$name'");
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['rollno'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['duration'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['mname'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>";?><img src="<?php echo $row["image"]; ?> " height="100" width="100"> <?php echo "</td>";
echo "</tr>";
}
}
else
{
echo "<tr><td colspan='4'> No Data Found , Please check your registration no. or contact the institute for clarification. ".$line.'</td></tr>';
}
mysqli_close($con);
}}
?>
name = htmlspecialchars($_POST['rollno']);
where are you getting this 'rollno??
i dont get why are you saving the result by posting['rollno'] because the name of your feild is 'name'.
change this line
$name = htmlspecialchars($_POST['rollno']);
to
$name = htmlspecialchars($_POST['name']);
I would like to know how can i put the table from mysql in a new file.php.
I want the MySql table to be on the page.
This is my code that inserts data in MySql.
<?php
// Create connection
$con = mysqli_connect("host", "id_", "password", "xxxxxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Task = $_POST['Task'];
$Date = $_POST['Date'];
$Desc = $_POST['Desc'];
$sql = "INSERT INTO tasklist (Task, Date, Description)
VALUES ('$Task', '$Date', '$Desc')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
<html>
<body>
<form action="addtask.php" method="post">
Task: <input type="text" name="Task">
Date: <input type="text" id="datepicker" name="Date">
Decrption:<textarea type="text" name="Desc"></textarea>
<input type="submit" value="submit">
</form>
</body>
</html>
Try this code:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
also u can try w3schools sample code :
Display the Result in an HTML Table
The following example selects the same data as the example above, but will display the data in an HTML table:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The output of the code above will be:
first code comes from "Jonnny" in this article
I am having problem in getting values from db. Iam new in php
I am using checkboxes to get values from database. Only checked values should be printed.
<form method="POST" action="gradoviexport.php" id="searchform">
<div id="GRADOVI BIH">
<h3>GRADOVI BOSNE I HERCEGOVINE</h3><hr/>
<input type="checkbox" name="gradovi[]" value="sarajevo"> Sarajevo
<input type="checkbox" name="gradovi[]" value="banovici"> Banovići
<input type="checkbox" name="gradovi[]" value="banjaluka"> Banja Luka
<input type="checkbox" name="gradovi[]" value="bihac"> Bihać
<input type="checkbox" name="gradovi[]" value="bileca"> Bileća
</div>
<div id="snimi">
<input type="submit" name="submit" value="EXPORT">
</div>
</form>
If Sarajevo is checked I want to print values from database. It does not have to be only one value checked If all values are checked it should print all values.
$con=mysqli_connect("$host","$username","$password", "$database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//connecting to db
$variable=$_POST['grad'];
foreach ($variable as $variablename)
{
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` = $variablename " ;
$queryRes = mysql_query($sql_select);
print"$sql_select";
}
echo "<table border='5'>
<tr>
<th>IME</th>
<th>PREZIME</th>
<th>FIRMA</th>
<th>ADRESA</th>
<th>TELEFON</th>
<th>FAX</th>
<th>MOBITEL</th>
<th>EMAIL </th>
<th>WEB_STRANICA </th>
<th>GRAD </th>
<th>KATEGORIJA </th>
</tr>";
while($row = mysqli_fetch_array($queryRes))
{
echo "<tr>";
echo "<td>" . $row['IME'] . "</td>";
echo "<td>" . $row['PREZIME'] . "</td>";
echo "<td>" . $row['FIRMA'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['TELEFON'] . "</td>";
echo "<td>" . $row['FAX'] . "</td>";
echo "<td>" . $row['MOBITEL'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "<td>" . $row['WEB_STRANICA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['KATEGORIJA'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
Assume you posted gradovi[] array values to submitted page.
Submit page:
$grad = array();
$grad = $_POST['gradovi']; //get array value
$grad = implode(',',$grad); //convert it into comma separated string
//Insert it into data base
Getting from database:
//fetch the gradovi field from the db like below
echo $row['gradovi']; // print all values
or
$grad = explode(',',$row['gradovi']);
foreach($grad as $check) {
echo $check; //print one by one
}
There is few errors in your code.
There is no escaping of the string from POST data. Use mysqli_real_escape_string
There is an error in your while loop. You redefining mysql query result.
Fixed code:
//connecting to db
$variable=$_POST['grad'];
foreach($variable as $key => $val) {
$variable[$key] = mysql_escape_string($val);
}
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` IN ('" . implode("','", $variable) . "')" ;
$queryRes = mysql_query($sql_select);
print"$sql_select";