I know that this question have been asked more times than amen in church. But i am gonna ask anyway.
I am going to an boardgame convention in Denmark and i figured "Hey we could use a locate a players SMS service"
So i build it. BUT when i have to take some data out of one Database like the phonenumber and the name. And i need to insert that into another Database (where my SMS injection looks) But a variable can only store 1 number and i need to store 10 ~ 50 numbers and Names
Here is what i got so far.
// escape variables for security
$Name = mysqli_real_escape_string($con, $_POST['Name']);
$Players = mysqli_real_escape_string($con, $_POST['Players']);
$Game = mysqli_real_escape_string($con, $_POST['Game']);
$besked = "Du har oprettet et spil med navn $Name og er et $Game som mangler $Players spiller(e).";
echo $besked;
echo "<br>";
$result = mysqli_query($con,"SELECT * FROM brugere where $Game = 'Ja'");
while($row = mysqli_fetch_array($result)) {
echo $row['Navn'] . " " . $row['VCNummer'];
echo "<br>";
$PhoneNumber = $row['Phonenumber'];
}
mysqli_close($con);
?>
<html>
<body>
<form action="smssend.php" method="post">
<input type="hidden" name="besked" value="<?php echo "$besked"; ?>"><br>
<input type="hidden" name="PhoneNumber" value="<?php echo "$PhoneNumber"; ?>"><br>
<input type="submit" value="Send data">
</form>
</body>
</html>
And when i am trying to put it in the other Database
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","SMSDATABASE");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$besked = mysqli_real_escape_string($con, $_POST["besked"]);
$PhoneNumber = mysqli_real_escape_string($con, $_POST["PhoneNumber"]);
$sql="INSERT INTO outbox (DestinationNumber, Class, TextDecoded)
VALUES ('$PhoneNumber', '1', '$besked')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
<meta http-equiv="refresh" content="0;url=../index.php">
I hope this makes sense.
I have tried the following
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DATABASE");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$Name = mysqli_real_escape_string($con, $_POST['Name']);
$Players = mysqli_real_escape_string($con, $_POST['Players']);
$Game = mysqli_real_escape_string($con, $_POST['Game']);
$besked = "Du har oprettet et spil med navn $Name og er et $Game som mangler $Players spiller(e).";
echo $besked;
echo "<br>";
$result = mysqli_query($con,"SELECT * FROM brugere where $Game = 'Ja'");
$phone_numbers = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$phone_numbers[] = $row['Phonenumber'];
}
mysqli_close($con);
?>
<html>
<body>
<form action="smssend.php" method="post">
<input type="hidden" name="besked" value="<?php echo "$besked"; ?>"><br>
<input type="hidden" name="PhoneNumber" value="<?php echo serialize($phone_numbers); ?>">
<input type="submit" value="Send data">
</form>
</body>
</html>
And the next PHP file
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","SMSDATABASE");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$besked = mysqli_real_escape_string($con, $_POST["besked"]);
$Phone = unserialize($_POST["PhoneNumber"]);
var_dump($Phone);
/*$sql="INSERT INTO outbox (DestinationNumber, Class, TextDecoded)
VALUES ('$PhoneNumber', '1', '$besked')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "Beskeden er sendt";
mysqli_close($con);
*/
?>
Please notice that i have canceled the insert into the database in this part.
But when i try to run the file i get the following
bool(false)
instead of this
while($row = mysqli_fetch_array($result)) {
echo $row['Navn'] . " " . $row['VCNummer'];
echo "<br>";
$PhoneNumber = $row['Phonenumber'];
}
try this
$phone_numbers = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$phone_numbers[] = $row['Phonenumber'];
}
then try a
var_dump($phone_numbers);
Related
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'm running a simple database search against one table in my database. The results are then displayed in a table. If no results are found, the search shows a message that says "0 results", but sometimes it will echo the table headings without displaying any results. This search is part of a class project and isn't going to be an active database, so I haven't included any protection for SQL injection. Any help would be greatly appreciated.
<h2>Customer Search</h2>
<br>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<table class="hoverTable"><tr><th>Client</th><th>Address</th><th>City</th><th>State</th><th>Zip Code<br></th><th>Phone</th></tr>';
// We have results! Go fetch rows!
while ($row = mysqli_fetch_row($result)) {
// This loop runs until there are no more results left to echo
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row["Address"]. "</td><td> " . $row["City"]. "</td><td> " . $row["State"]. "</td><td> " . $row["ZipCode"]. "</td><td> " . $row["Phone"]. "</td></tr>";
}
echo "</table>";
}
} else {
// No results from query
$message = "0 results";
}
/* free result set */
mysqli_free_result($result);
}
}
?>
</div>
</div>
<div class="center">
<?php
if(isset($message)){ echo $message; }
?>
</div>
</body>
</html>
I find, and you may disagree, but properly indenting your code as you go and opening and closing tags before filling in content help reduce the number of problems. Having said that now it'll probably not work!
<html>
<head>
<title>db search</title>
</head>
<body>
<div>
<div>
<h2>Customer Search</h2>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
$conn = new mysqli( $servername, $username, $password, $dbname );
if ( $conn->connect_error ) die("Connection failed: " . $conn->connect_error );
if( isset( $_POST['search'] ) ) {
$searchq = $_POST['search'];
$searchq = preg_replace( "#[^0-9a-z]#i", "", $searchq );
$sql = "SELECT * FROM `Customers` WHERE `Client` LIKE '%$searchq%';";
if ( $result = mysqli_query( $conn, $sql ) ) {
if ( mysqli_num_rows( $result ) > 0 ) {
echo '
<table class="hoverTable">
<tr>
<th>Client</th>
<th>Address</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Phone</th>
</tr>';
while( $row = $result->fetch_assoc() ) {
echo "
<tr>
<td>".$row["Client"]."</td>
<td>".$row["Address"]."</td>
<td>".$row["City"]."</td>
<td>".$row["State"]."</td>
<td>".$row["ZipCode"]."</td>
<td>".$row["Phone"]."</td>
</tr>";
}
echo '
</table>';
} else {
$message = "0 results";
}
}
mysqli_free_result( $result );
}
?>
</div>
</div>
<div class="center">
<?php if( isset( $message ) ){ echo $message; } ?>
</div>
</body>
</html>
Delete the redundant first while loop while ($row = mysqli_fetch_row($result)) {, if the query had just 1 result the first loop would have fetched it only while the 2nd while loop would have fetched nothing resulting in just a header and no body of the table.
<h2>Customer Search</h2>
<br>
<p class="first">Search the Customer Database</p>
<form action="searchcustomers.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customers WHERE Client LIKE '%$searchq%'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
echo '<table class="hoverTable"><tr><th>Client</th><th>Address</th><th>City</th><th>State</th><th>Zip Code<br></th><th>Phone</th></tr>';
// We have results! Go fetch rows!
// This loop runs until there are no more results left to echo
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row["Address"]. "</td><td> " . $row["City"]. "</td><td> " . $row["State"]. "</td><td> " . $row["ZipCode"]. "</td><td> " . $row["Phone"]. "</td></tr>";
}
echo "</table>";
} else {
// No results from query
$message = "0 results";
}
/* free result set */
mysqli_free_result($result);
}
}
?>
</div>
</div>
<div class="center">
<?php
if(isset($message)){ echo $message; }
?>
</div>
</body>
</html>
I am new to PHP and SQL and trying to figure out how I can make the HTML Approve (submit) button interact specifically with its corresponding record. Currently when the Approve button is clicked, each of the fields are updated, but the top (first) record available is always the one updated. I would like the user to be able to skip the first record and update a different record. Any and all suggestions/help are greatly appreciated.
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('there was a problem connecting to the database' . mysql_error());
$sql = "SELECT Part, Lot, Qty, AnodTemp, Amp, SealTemp, PerformedBy, DateTimePerformed, FinalAnodThickness, QtyPass, FinalSealCheck, CheckedBy, DateTimeChecked, id FROM logs";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$unapproved = $row['CheckedBy'];
if($unapproved == null)
{
echo "<br><br><br> Part: " . $row['Part']. " / Lot: " . $row['Lot']. " / Qty: " . $row['Qty']. " / AnodTemp: " . $row['AnodTemp']. " / Amp: " . $row['Amp']. " / SealTemp: " . $row['SealTemp']. " / PerformedBy: " . $row['PerformedBy']. " / ID: " . $row['id']; ?>
<form action="adminapproval.php" method="post">
Final Anod Thickness:<br>
<input type="text" name="FinalAnodThickness">
<br><br>
Qty Pass:<br>
<input type="text" name="QtyPass">
<br><br>
Final Seal Check:<br>
<input type="text" name="FinalSealCheck">
<br><br>
<input type="submit" id="submit" value="Approve" name="submit">
<br><br>
</form>
_____________________________________________________________________<br>
<?php
if (isset($_POST['submit']))
{
$FinalAnodThickness= $_POST['FinalAnodThickness'];
$QtyPass= $_POST['QtyPass'];
$FinalSealCheck= $_POST['FinalSealCheck'];
$CheckedBy= $_SESSION['CheckedBy'];
$id = $row['id'];
$sql = "UPDATE logs SET FinalAnodThickness = '$FinalAnodThickness', QtyPass = '$QtyPass', FinalSealCheck = '$FinalSealCheck', CheckedBy = '$CheckedBy', DateTimeChecked = now() WHERE id = $id ";
$conn->query($sql);
break;
$conn->close();
echo "Record Updated.";
header("Location: adminapproval.php");
}
}
}
}
echo "<br><br> No further items need to be approved at this time.";
?>
TWO FILES
adminapproval.php
<?php
session_start();
$conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('there was a problem connecting to the database' . mysql_error());
$sql = "SELECT Part, Lot, Qty, AnodTemp, Amp, SealTemp, PerformedBy, DateTimePerformed, FinalAnodThickness, QtyPass, FinalSealCheck, CheckedBy, DateTimeChecked, id FROM logs";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$unapproved = $row['CheckedBy'];
if($unapproved == null){
echo "<br><br><br> Part: " . $row['Part']. " / Lot: " . $row['Lot']. " / Qty: " . $row['Qty']. " / AnodTemp: " . $row['AnodTemp']. " / Amp: " . $row['Amp']. " / SealTemp: " . $row['SealTemp']. " / PerformedBy: " . $row['PerformedBy']. " / ID: " . $row['id']; ?>
<form action="adminapproval-exec.php?id=<?php echo $row['id']; ?>" method="post">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>" />
<input type="hidden" name="checkedby" value="<?php echo $SESSION['CheckedBy']; ?>" />
Final Anod Thickness:<br>
<input type="text" name="FinalAnodThickness">
<br><br>
Qty Pass:<br>
<input type="text" name="QtyPass">
<br><br>
Final Seal Check:<br>
<input type="text" name="FinalSealCheck">
<br><br>
<input type="submit" id="submit" value="Approve" name="submit">
<br><br>
</form>
<?php
}
}
} else {
echo "<br><br> No further items need to be approved at this time.";
}
?>
adminapproval-exec.php
<?php
session_start();
if (isset($_POST['submit'])){
$FinalAnodThickness= $_POST['FinalAnodThickness'];
$QtyPass= $_POST['QtyPass'];
$FinalSealCheck= $_POST['FinalSealCheck'];
$CheckedBy= $_POST['CheckedBy'];
$id = $_GET['id'];
// OR
// $id = $_POST['id'];
$sql = "UPDATE logs SET FinalAnodThickness = '$FinalAnodThickness', QtyPass = '$QtyPass', FinalSealCheck = '$FinalSealCheck', CheckedBy = '$CheckedBy', DateTimeChecked = now() WHERE id = $id ";
$conn->query($sql);
$conn->close();
// echo "Record Updated.";
header("Location: adminapproval.php");
}
?>
<?php
$server = "localhost";
$username = "username";
$password = "password";
$dbname = "db";
$con = mysqli_connect($server, $username, $password, $dbname);
if (!$con) {
die("Faild: " . mysqli_connect_error());
}
$sql = "UPDATE xxx SET lastname='Jan' WHERE id=2"; // This is importat
if (mysqli_query($con, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($con);
}
mysqli_close($con);
?>
$CheckedBy= $_SESSION['CheckedBy'];
$id = $row['id'];
Should the row id be coming out of the session as well? If not, then it will always be pointing to the first item in the row.
i am trying to submit data from a html form using php to a sql database.
It completed up to part 5 but doesn't appear to be any actual data in any of the table rows apart from the auto increment userID. Also is this code protected from SQL Injection?
Also what is the best way to input a datestamp into the SQL database? for example a ClientSince field.
Here is my clientsubmit.php
<?php
// Create connection
echo "Made it! Part 1";
$con=mysqli_connect("xxx","xxx","xxx","xxx");
echo "Made it! Part 2";
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$txtNam = mysql_real_escape_string($_POST["name"]);
$txtEmail = mysql_real_escape_string($_POST["email"]);
$txtSlots = mysql_real_escape_string($_POST["slotcount"]);
$txtSecurity = mysql_real_escape_string($_POST["passcode"]);
echo "Made it! Part 3";
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
echo "Made it! Part 4";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Made it! Part 5";
mysqli_close($con);
?>
And here is my form:
<form name="form" class="form" action="clientsubmit.php" method="post">
<input type="text" name="sum2" readonly hidden="true" onChange="updatesum()" value="1.5"/><br>
Ingame Name: <input type="text" name="name" class="txtbox" /><br><br>
Email Address: <input type="text" name="email" class="txtbox" /><br><br>
Passcode: <input type="text" name="passcode" class="txtbox2" /><br><br>
Slot Count: <input type="text" name="slotcount" onChange="updatesum()" class="txtbox2" value="10"/><br><br>
Per Month: <input name="sum" readonly class="txtboxtotal" style="border: 0px;" value="15"> Million<br><br>
<input type="submit">
</form>
Added these:
echo "Made it here! 3 ";
echo " ";
echo $txtNam;
echo " ";
echo $txtEmail;
echo " ";
echo $txtSlots;
echo " ";
echo $txtSecurity;
echo " ";
and it appears that the variables are not holding any data before submitted to the database.
Got it working with the help of you guys, here is the finished code:
<?php
// Create connection
$con=mysqli_connect("xxxx","xxxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con, $_POST["email"]);
$txtSlots = mysqli_real_escape_string($con, $_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con, $_POST["passcode"]);
$sql = "INSERT INTO accounts (name, email, slotCount, securityCode) Values('$txtNam','$txtEmail','$txtSlots','$txtSecurity')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
The issue is you are using mysql_real_escape_string() and using mysqli_*()
change mysql_real_escape_string() to mysqli_real_escape_string()
$txtNam = mysqli_real_escape_string($con, $_POST["name"]);
$txtEmail = mysqli_real_escape_string($con,$_POST["email"]);
$txtSlots = mysqli_real_escape_string($con,$_POST["slotcount"]);
$txtSecurity = mysqli_real_escape_string($con,$_POST["passcode"]);
You mentioned above submit.php and you post form at clientsubmit.php.
I am making a recipe site at the moment and am struggling to get my comment function to work, I previously had it working until but now I keep getting an error which tells me I cannot access the database when I try and submit a comment
I know this might seem quite simple but I'm completely stuck I've been trying to figure out a way round this for weeks but really am not making any headway..
Here the PHP process:
if (!$db_server){
die("unable to Connect to MYSQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
if(trim($_POST['submit']) =="submit"){
}else{
if (isset($_POST['dropoption']) && ($_POST['dropoption'] != '')){
if (isset($_POST['meal']) && ($_POST['meal'] != '')) {
$dropoption = clean_string($db_server, $_POST['dropoption']);
$meal = clean_string($db_server, $_POST['meal']);
$quer = "SELECT * FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal'LIMIT 0,1";
mysqli_select_db($db_server, $db_database);
$querya= mysqli_query($db_server, $quer);
if (!$querya) die("database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($querya)){
$recipeid .= $row['recipeid'];
$recipename .="<h1>". "Why dont you have ".$row['mealname']."</h1>";
$ingredients .="<p>".$row['ingredients']."</p>";
$recipe .="<p>" .$row['recipe']."</p>";
$cookingtime .="<h4>" .$row['hours']." Hours".$row['minutes']." Minutes </h4>";
$mealpic .="<img src='http://ml11maj.icsnewmedia.net/Workshops/Week%207/".$row['imagepath']."'/>";
}
if ($comment != ''){
$userid = trim($_SESSION['userid']);
$comment = trim($_POST['comment']);
$userid = clean_string($db_server, $_SESSION['userid']);
$comment = clean_string($db_server, $_POST['comment']);
$query = "INSERT INTO Comments (comment,userid,recipeid) VALUES ('$comment','$userid','$receipeid')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
}
}//if(meal)//
}//if(cuisine)//
} //if(trim)//
}
$query = "SELECT * FROM Comments";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)) {
$str_comments .= "<p>" . $row['comment'] . "</p>";
}
and here is the html form:
<?php echo $recipename;
echo $mealpic;
?>
<h2>Ingredients</h2>
<?php
$ingredientchunks = (explode(",",$ingredients));
for($i = 1; $i < count($ingredientchunks); $i++){
echo "$i.$ingredientchunks[$i] <br/>";}
echo $cookingtime;
?>
<h2>Recipe</h2>
<?php
$recipechunks = (explode(",",$recipe));
for($i = 1; $i < count($recipechunks); $i++){
echo "$i.$recipechunks[$i] </br>";}
?>
<form id="results" form method="post" action="results.php">
<input type="submit" id="Like" name="Like" value="Like" />
<input type="submit" id="Next" name="Next" value="Next" />
</form>
<div id=Comments>
<form id="comments" form method="post" action='results.php?cuisine_type=" . $dropoption ."b_l_d=" . $meal . "'>
Comment: <textarea rows="2" cols="30" name="comment" id="comment" placeholder="Anything to say??"></textarea>
<input type="submit" id="comments" name="comments" value="comments" />
</form>
<?php
echo $str_comments;
require_once "db_close.php";
?>
</div>
</p>
<? require_once ('home_stop.php')?>