text versioning system using PHP MySQL - php

I am trying to create a system where a user can enter some text and another user can edit that input and another can edit the input that the second user has entered. This is the code that I have so far; it only works as a reply system to a post at the moment:
<?php
include 'includes/connection.php';
$query = "SELECT * FROM branches";
$result1 = mysql_query($query) or die(mysql_error());
while($person = mysql_fetch_array($result1)) { //As long as there is data, output the data
$id = $person['ID'];
$query2 = "SELECT * FROM branchesedit WHERE (parent_id = '$id' )";
$result2 = mysql_query($query2) or die(mysql_error());
echo "<h3>" . $person['Names'] . "</h3>";
echo "<p>" . $person['Lyrics'] . "</p>";
echo "Modify Song";
echo "<span> </span>";
echo "Delete Song";
while($row2 = mysql_fetch_array($result2)){
echo "<h3>" . $row2['Name'] . "</h3>";
echo "<p>" . $row2['LyricUpdate'] . "</p>";
}
}
?>
modify.php
<?php
if(isset($_POST['submit'])) {
$query = "SELECT ID FROM branches WHERE ID = $_GET[id]";
mysql_query("INSERT into branchesedit(`IDs`, `Name`, `LyricUpdate`, `parent_id`)
VALUES ('','$_POST[inputName]', '$_POST[ta]', '$_POST[id]')") or die(mysql_error());
echo "Song has been modified";
header("Location: index.php");
}
?>

Note:
You are using an isset() function on your modify.php where in your first given code (guessing your index.php) does not have a submit button. Only has a link that will redirect users to modify.php.
Better include a connection in your modify.php to establish connection so you can run your query.
You should consider using mysqli_* prepared statement rather than the deprecated mysql_* functions to prevent SQL injections.
Your modify.php in prepared statement:
<?php
/* INCLUDE HERE YOUR CONNECTION */
if(!empty($_GET['id'])) {
if($stmt = $con->prepare("SELECT IDs, Name, LyricUpdate FROM branchesedit WHERE parent_id = ? ORDER BY IDs DESC")){
$stmt->bind_param("i",$_GET["id"]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id,$name,$lyricupdate);
$stmt->fetch();
?>
<h1>Modified by: <?php echo $name; ?></h1>
<form action="modify.php" method="POST">
<input type="hidden" name="id" value="<?php echo $_GET["id"]; ?>">
<input type="text" name="inputName" value="<?php echo $name; ?>"><br>
<textarea name="ta"><?php echo $lyricupdate; ?>"></textarea><br>
<input type="submit" name="submit">
</form>
<?php
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF NOT EMPTY ID */
if(isset($_POST["submit"])){
if($stmt = $con->prepare("INSERT into branchesedit (`Name`, `LyricUpdate`, `parent_id`)
VALUES (?,?,?)")){
$stmt->bind_param("ssi",$_POST["inputName"],$_POST["ta"],$_POST["id"]);
$stmt->execute();
$stmt->close();
} /* END OF INSERT PREPARED STATEMENT */
echo "Song has been modified";
header("LOCATION: index.php");
} /* END OF ISSET SUBMIT */
?>
Summary:
When a user clicks on Modify Song link, user will be redirected to modify.php and then runs a query that will select the latest edit from your table branchesedit based from the ID being passed from the link.
User will see a form that is already filled up based from the last edit.
When submitted, it will still be in the modify.php and then runs an insert query.
After the insert query, it will redirect back to index.php
Replace the necessary connection variable I used in the prepared statement:
Example of your connection to be included in your queries (connection.php):
$con = new mysqli("Yourhost", "Yourusername", "Yourpassword", "Yourdatabase");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

Related

Delete a users data from SQL using PHP

Hi im trying to delete a users booking detials when the user clicks delete in my bookingbeforedeltion.php file but for some reason when I test my php file once I click delete it goes to my delete.php screen and says it failed to delete from database and has the error Undefined index: rn. Is my rn not defined? Sorry Im new to this. Here is my code below:
bookingbeforedeltion.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
<body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$query = 'SELECT roomname, checkindate, checkoutdate FROM booking';
$result = mysqli_query($DBC,$query);
if (mysqli_num_rows($result) > 0) {
echo "Delete Bookings" ?><p><?php
while ($row = mysqli_fetch_assoc($result)) {
echo "Room name: ".$row['roomname'] . PHP_EOL;
echo "Check in date: ".$row['checkindate'] . PHP_EOL;
echo "Check out date: ".$row['checkoutdate'] . PHP_EOL;
?>
[Cancel]
<?php
echo "<hr />";
}
mysqli_free_result($result);
}
echo "</pre>";
echo "Connectted via ".mysqli_get_host_info($DBC);
mysqli_close($DBC);
?>
</body>
</html>
delete.php:
<!DOCTYPE HTML>
<html><head><title>BookingBeforeDeletion</title> </head>
body>
<?php
include "config.php";
$DBC = mysqli_connect("127.0.0.1", DBUSER , DBPASSWORD, DBDATABASE);
if (!$DBC) {
echo "Error: Unable to connect to MySQL.\n".
mysqli_connect_errno()."=".mysqli_connect_error() ;
exit;
};
echo "<pre>";
$roomname=$_GET['rn'];
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
$result = mysqli_query($DBC,$query);
if($result)
{
echo "<font color='green'> Booking deleted from database";
}
else {
echo "<font color='red'> Failed to delete booking from database";
}
?>
and I think this will help:
As mentioned above, you need to print it from the PHP
<a href= 'delete.php?rn=$result[roomname]'>
// To
<a href= 'delete.php?rn=<?= $row['roomname'] ?>'>
// Explanation:
// 1. <?= ... ?> is the short form of <?php echo ... ?>
// 2. The `roomname` came from $row, not $result ($result is the MySQLi Object)
// 3. You need to quote the `roomname` because without it `roomname` will be readed
// as Constant, and may Throw a Warning message
//
Your DELETE is incorrect, the correct one is DELETE FROM ... WHERE ...
$query = "DELETE bookingID, roomname, checkindate, checkoutdate, contactnumber,
bookingextras, roomreview, customerID, roomID FROM booking WHERE roomname =
'$roomname'";
// To
$query = "DELETE FROM booking WHERE roomname = '$roomname'";
EXTRA:
3. You can assign a default value to $roomname
$roomname=$_GET['rn'];
// To
$roomname=$_GET['rn'] ?? 'default if null';
// if the rn index doesnt exist, the $roomname value will be `default if null` instead of throwing a Warning
Try to use Prepared-Statement SQL instead of writing it. (I dont know the example, but it can prevent SQL Injection)

Delete row when pressing button not working

So currently 160 servers are pulled from a database and stacked under each other:
<tr>
<td>
The last <td> in this row should trigger the removal of that specific row from the database but it doesn't and links me to the error page at this time.
Main code:
<?php
require_once "config/config.php";
$sql = "SELECT * FROM deployments";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['server'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['url'] . "</td>";
echo "<td>" . $row['port'] . "</td>";
echo "<td><span class='badge badge-warning'>ERROR</span></td>";
echo "<td><a href='config/delete.php?id=". $row['server'] ."' title='Delete Record' data-toggle='tooltip'><span class='fa fa-trash'></span></a></td>";
echo "</tr>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>
Delete.php page code:
<?php
// Process delete operation after confirmation
if(isset($_POST["server"]) && !empty($_POST["server"])){
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_server);
// Set parameters
$param_server = trim($_POST["server"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else{
// Check existence of id parameter
if(empty(trim($_GET["server"]))){
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
When the fa fa-trash icon is clicked the row that icon shares with the server name url port should be removed from the database.
You should use $_GET['id'] or $_REQUEST['id'] instead of $_POST["server"]
Replace your Delete.php code with below code
<?php
// Process delete operation after confirmation
if (isset($_GET["id"]) && !empty($_GET["id"])) {
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = ?";
if ($stmt = mysqli_prepare($link, $sql)) {
// Set parameters
$param_server = trim($_GET["id"]);
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_server);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else {
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else {
// Check existence of id parameter
if (empty(trim($_GET["id"]))) {
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
I've made some changes to the code myself, thanks for all the help, the removal is still not working and I keep getting the error message from the error.php page.
<?php
// Process delete operation after confirmation
if (isset($_GET["id"]) && !empty($_GET["id"])) {
$id = $_POST["id"];
// Include config file
require_once "config/config.php";
// Prepare a delete statement
$sql = "DELETE FROM deployments WHERE id = '$id'";
if ($stmt = mysqli_prepare($link, $sql)) {
// Set parameters
$param_id = trim($_GET["id"]);
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "i", $param_id);
// Attempt to execute the prepared statement
if (mysqli_stmt_execute($stmt)) {
// Records deleted successfully. Redirect to landing page
header("location: ../deployments.php");
exit();
} else {
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
} else {
// Check existence of id parameter
if (empty(trim($_GET["id"]))) {
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="alert alert-danger fade in">
<input type="hidden" name="id" value="<?php echo trim($_GET["id"]); ?>"/>
<p>Are you sure you want to delete this record?</p><br>
<p>
<input type="submit" value="Yes" class="btn btn-danger">
No
</p>
</div>
</form>
Change your code to...
// Process delete operation after confirmation
if(isset($_POST["id"]) && !empty($_POST["id"])) {
$id = $_POST["id"];
//Include config file
require_once("config/config.php");
//Prepare a delete statement
$sql = "DELETE FROM deployments WHERE server = '$id' ";

If there is no $_POST present after a URL, how can I prevent (nothing) from getting passed into a MySQL query, and causing an error?

I have a Delete.php page that deletes records based on their ID.
When there is an ID, i.e., Delete.php?id=3610, all is well, and it functions as expected.
If I just go to "Delete.php" and that's it - no ID, it generates:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1"
From the little I understand, it is doing this because I am trying to pass a nonexistent variable into my query.
I have been trying to put if (empty($_POST['id'])) { } in different places, which removes the error, but breaks something else.
Here is my code:
<?php
require_once 'functions.php';
$conn = mysqli_connect("localhost", "user", "pass",'db');
writeHead("Delete Track");
if (isset($_POST['delete'])) {
$trkid = $_POST['trkid'];
$query = "DELETE FROM track WHERE TrackID=$trkid";
mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn)>0) {
header("Location: Display.php?action=deleted&id=$trkid&status=deleted");
exit();
}
echo "<p class='error'>Unable to update record</p>";
} else {
if (!isset($_GET['id'])) {
echo "<p class='error'>No Track ID provided.<br><a href='Display.php'>Return to display page.</a><p>";
}
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}
?>
<p>Track Information:</p>
<p><?php echo "<b>ID: $trkid <br>Title: $Name</b>"; ?></p>
<form method="post" action="Comp3Delete.php">
<p>
<input type="hidden" name="trkid" value="<?php echo $trkid; ?>">
<input type="submit" name="delete" class="btn" value="Confirm Delete">
</p>
</form>
<p>Return to Track Table Display</p>
<?php writeFoot(); ?>
Your post code is fine. it's the GET code that's wrong:
if (!isset($_GET['id'])) {
^^^^^^^^--check if the parameter exists
}
$trkid=$_GET['id'];
^---try to use the parameter ANYWAYS, even if it doesn't exist.
$trkid=$_GET['id']; has no condition so it runs even when no id is passed which generates the error. Your code should go like this:
if(isset($_GET['id'])){
$trkid=$_GET['id'];
$query = "SELECT * FROM track WHERE TrackID=$trkid";
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if (mysqli_num_rows($result)> 0) {
$row = mysqli_fetch_assoc($result);
$Name=$row['Name'];
$Album=$row['AlbumId'];
$Composer=$row['Composer'];
$Milli=$row['Milliseconds'];
$Bytes=$row['Bytes'];
$UnitPrice=$row['UnitPrice'];
} else {
echo "<p class='error'>Unable to retrieve Track $trkid.<br><a href='Display.php'>Return to display page.</a>";
}
}

Getting an error of SQl Syntax

Getting an error of
"Error: 1
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
Please help guys, Many thanks in advance.
Code:
<?php
include('head.php');
if(isset($_POST['submit']))
{
$userid = trim($_POST['userid']);
$email = trim($_POST['email']);
$mobile = trim($_POST['mobile']);
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>******</title>
<link href="forum-styles.css" rel="stylesheet" type="text/css">
</head>
<style type="text/css">
.txtField {
padding: 5px;
border:#fedc4d 1px solid;
border-radius:4px;
}
</style>
<body background="img/gold-and-money.jpg">
<form action="" method="post" class="basic-grey">
<h1>****** Forgot Password
<span>Please let us know your UserId, We will reset password and inform you.</span> </h1>
<label>
<span>User Id :</span>
<input type="text" name="userid" required />
</label>
<label>
<span>Mobile N. :</span>
<input type="text" name="mobile" required/>
</label>
<label>
<span>Email Id :</span>
<input type="text" name="email" required/>
</label>
<label>
<div align="right"><span> </span>
<input type="submit" class="button" value="Submit" name="submit"/>
</div>
</label>
</form>
</body>
</html>
$sql = mysqli_query($conn,"INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')");
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You've got two calls here to mysqli_query. The first time, you're making the query and assigning the return value to $sql; the second time, you're running $sql as a query.
To fix the immediate problem, do something along the lines of:
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
You're assigning your query to a string, and then using that in your query. This makes debugging things easier, as you can now output your generated query to check what you're producing.
However
You're also passing user-generated data directly into an SQL query, without escaping it. This is very bad - at best, you're going to have a problem if some of the data contains apostrophes. At worst, your database will get hacked. One solution here is to use escaping, as Fred suggested, using mysqli_real_escape_string:
$userid = mysqli_real_escape_string($conn, $_POST['userid']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
I'd suggest also looking at using bound parameters and a prepared statement instead, for added extra security.
Use prepared statements, or PDO with prepared statements, they're much safer.
#andrewsi answered correct: "You're running your query twice. The first time, you're assigning the result to $sql; the second time, you're trying to run that result as a query."
#andrewsi, you r running your query twice and your your query contains variables which you have make them as literals. so code would be like this:
$sql ="INSERT INTO forgot(userid,email,mobile)VALUES ($userid,$email,$mobile)";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
I hope this will help you.
Here is a basic example. Check where you have a turn. Always keep follow the standard way of coding.
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
/* drop table */
$mysqli->query("DROP TABLE myCity");
/* close connection */
$mysqli->close();
?>
Ankit, their are few things to take care of while coding the queries, instead of explaining them, I will try to rewrite the query:
$query = sprintf("INSERT INTO forgot('userid','email','mobile')
VALUES ('%s', '%s', '%s')"
, mysqli_real_escape_string( $con, $_POST['userid'] )
, mysqli_real_escape_string( $con, $_POST['email'] )
, mysqli_real_escape_string( $con, $_POST['mobile'] ));
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted" . mysqli_affected_rows($conn) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
if in case, userid is the integer, convert the userid to int as follows before creating the $query:
$userid = (int)$_POST['userid'];
$sql = "INSERT INTO forgot(userid,email,mobile)VALUES ('$userid','$email','$mobile')";
if (mysqli_query($conn,$sql))
{
echo "We will Contact you Soon.<br>";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
It will work.

Trying to create a simple cumulative addition script in PHP (or JS):

Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>

Categories