I'm a beginner at coding (I just have a small experience with Visual Basic and Pascal) and now I'm trying to learn some Web Development using O'Reilly's book "Learning PHP, MySQL, JavaScript, CSS & HTML 5".
The problem is that he is using MySQL instead of MySQLi, so I need to do small changes when I'm following thought the exercises.
In a chapter called "Accessing MySQL databases using PHP" he built a form where the user can add a new book (with title name, author, year, category and ISBN) to the database. My problem is that I have some error than doesn't allow to see in the web page the new book submitted.
I'm not sure, but I think it has to be something with the get_post and mysqli_real escape_string part.
This is the code I've written:
<?php //sqltest.php
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysqli_error($db_server));
mysqli_select_db($db_server, $db_database)
or die ("Unable to select database: " . mysqli_error($db_server));
//Deleting a record.
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post('isbn');
$query = "DELETE FROM classics WHERE isbn = '$isbn'";
if (!mysqli_query($db_server,$query))
echo "DELETE failed: $query<br>" .
mysqli_error($query) . "<br><br>";
}
//Add new elements to the database.
if (isset($_POST['author']) && //Isset -> Determine if a variable is set and is not NULL.
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($db_server, 'author');
$title = get_post($db_server, 'title');
$category = get_post($db_server, 'category');
$year = get_post($db_server, 'year');
$isbn = get_post($db_server, 'isbn');
}
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
//Displaying the form.
echo <<<_END
<form action = "sqltest.php" method="post"> <pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Category <input type="text" name="category" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type="submit" value="ADD RECORD" />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database acess failed: " . mysqli_query_error($result));
$rows = mysqli_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysqli_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
function get_post($db_server, $var)
{
return mysqli_real_escape_string($db_server, $_POST[$var]);
}
mysqli_close($db_server);
?>
Just to explain my problem better: I fill the form with the details from the new book and then I submitted it but the new book doesn't appear on the web page (like the ones added before using MySQL command line).
Thanks for your time,
David
There is an error in your code, specific the name of database columns.
$query = "INSERT INTO classics (author, title, category, year, isbn) VALUES ('$author', '$title', '$category', '$year', '$isbn');";
PHP trying to connect to MySQL database! but the code doesn't work.
Here is the code, when I put the code in a PHP file, the display shows actually the code I wrote.
I am stuck, please help!
<?php // sqltest.php
require_once '../../htdocs/login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
if (isset($_POST['delete']) && isset($_POST['isbn']))
{
$isbn = get_post($conn, 'isbn');
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>" .
$conn->error . "<br><br>";
}
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post($conn, 'author');
$title = get_post($conn, 'title');
$category = get_post($conn, 'category');
$year = get_post($conn, 'year');
$isbn = get_post($conn, 'isbn');
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$category', '$year', '$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: $query<br>" .
$conn->error . "<br><br>";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author">
Title <input type="text" name="title">
Category <input type="text" name="category">
Year <input type="text" name="year">
ISBN <input type="text" name="isbn">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="isbn" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
$result->close();
$conn->close();
function get_post($conn, $var)
{
return $conn->real_escape_string($_POST[$var]);
}
?>
I am reading this book called Learning PHP, MySQL, & JavaScript
4th Edition By Robin Nixon, but when I write the exact code, it doesn't show like in the book but I get that like in the photo. I am trying to connect MySQL with PHP, using xampp. I created also the php.login file. I wrote my username and password, and saved it in the same directory with this code!
please help
Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck
i have Form what populate fields from database, can you show me php to insert data to database, each score to own row in database (id,name,score)
Updated: whit theis codes it prints like this:
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
now i use this form:
<form action="insert_action2.php" id="form2" title="form2" method="post">
<table>
<?php
$link = mysqli_connect("localhost", "form", "form", "form");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM form2" ;
$players = $link->query($sql);
while($player = $players->fetch_assoc()){
?>
<tr>
<td>
<input type="text" name="id" id="id" value="<?php echo $player["id"]; ?>">
<input type="text" name="name" id="name" value="<?php echo $player["name"]; ?>">
</td>
<td>
<input type="text" name="score" id="score" size="2" value="<?php echo $player["score"]; ?>">
</td>
</p>
<?php
}
$link->close();
?>
</tr>
</table>
<input type="submit" value="update scores">
</form>
insert to database -insert_action2.php
i have tried couple arrays and foreach but cant get those working right...
<?php
foreach($_POST as $players => $value) {
$id = mysqli_real_escape_string($link, $_POST['id']);
$name = mysqli_real_escape_string($link, $_POST['name']);
$score = mysqli_real_escape_string($link, $_POST['score']);
$sql = "UPDATE form2 SET score='$score', name='$name' WHERE id=$id";
if(mysqli_query($link, $sql)){
echo "lines updated to database: <br>$id - $name - $score <br><br><p><p>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
You'll need to use:
$sql = "insert into `form2`(`name`, `score`) VALUES ('{$name}', '{$score}')";
When you use some variable inside a string, you need to scape the variable.
Or use this way:
$sql = "insert into `form2`(`name`, `score`) VALUES ('" . $name . "', '" . $score . "')";
I am new to PHP and I am following a tutorial that gets information from a mySQL database table by the row and outputs a form to create new table rows. For some reason I can't figure out what is wrong with my code? The page is blank when I refresh the page and I have been staring at this code forever. Does anybody know what I am doing wrong? The database connection is fine as it is used on another page and i have checked.
The mySQL database I have is extremely simple, with 1 table called users that has 5 columns (ID, username, firstName, lastName, title) with the ID being a unique field.
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['delete']) && isset($_POST['ID']))
{
$id = get_post('ID');
$query = "DELETE FROM users WHERE ID='$id'";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>" .
mysql_error() . "<br><br>";
}
if (isset($_POST['ID']) &&
isset($_POST['username']) &&
isset($_POST['firstName']) &&
isset($_POST['lastName']) &&
isset($_POST['title']))
{
$id = get_post('ID');
$username = get_post('username');
$firstName = get_post('firstName');
$lastName = get_post('lastName');
$title = get_post('title');
$query = "INSERT INTO users VALUES" .
"('$id', '$username', '$firstName', '$lastName', '$title')";
if (!mysql_query($query, $db_server))
echo "INSERT failed: $query<br>" .
mysql_error() . "<br><br>";
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
ID <input type="text" name="ID">
username <input type="text" name="username">
firstName <input type="text" name="firstName">
lastName <input type="text" name="lastName">
title <input type="text" name="title">
<input type="submit" value="ADD RECORD">
</pre></form>
_END;
$query = "SELECT * FROM users";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
ID $row[0]
username $row[1]
firstName $row[2]
lastName $row[3]
title $row[4]
</pre>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="title" value="$row[4]">
<input type="submit" value="DELETE RECORD"></form>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
Any help would be super awesome!
You are trying to retrieve variables with the wrong way.
Example
$username = get_post('username');
should be
$username = $_POST['username'];
You should do the same with the same code that you are trying to retrieve post variables.
And the query to insert values should be
$query = "INSERT INTO users VALUES('".$id."', '".$username."', '".$firstName."', '".$lastName."', '".$title."')";