UPDATE
Added all the code for the img upload as well as adding to the DB.
The output of print_r($_POST); :Array ( [prodName] => Test Product [prodPrice] => 100 [prodDescript] => Test description [submit] => UPLOAD )
Also the prodID col is auto increment.
Building off an image uploader you all so graciously helped me with, I am now trying to get the rest of this form to work. I am sending the data via POST but none of the info is being sent. I have verified the images upload, via the $_FILES array, but nothing is coming through in the $_POST data
I know my hosting service allows $_POST because I have another form that works perfectly with it. I cannot get to seem to get any errors to point me in the right direction. So once again. I come to you wonderful people.
<form action="inventory_add.php" method="POST" enctype="multipart/form-data">
<label>Product Name: </label>
<input type="text" name="prodName" id="prodName">
<br>
<label>Product Price: </label>
<input type="text" name="prodPrice" id="prodPrice">
<br>
<label>Product Description</label><br>
<textarea name="prodDescript" width="200px" id="prodDescript"></textarea>
<br>
Select Image Files to Upload:
<br>
<input type="file" name="upload[]" multiple >
<input type="submit" name="submit" value="UPLOAD">
</form>
Some of the code from inventory_add.php:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "**********";
$username = "**********";
$password = "***********";
$dbname = "************";
$prod_name = $_POST['prodName'];
$prod_price = $_POST['prodPrice'];
$prod_descript = $_POST['prodDescript'];
print_r($_POST);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if(isset($_FILES['upload'])){
$total = count($_FILES['upload']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "images/prod/" . $_FILES['upload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$img_names = implode(",",$_FILES['upload']['name']);
}
}
}
$prodID = $_SESSION['curcount'] + 1;
$sql = "INSERT INTO `inventory` (`prodId`, `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (' '," . $prod_name. "," . $prod_descript . "," . $prod_price ."," .$img_names.")";
if ($conn->query($sql) === TRUE) {;
// header('location:http://nerdsforhire.pnd-productions.com/shopmgr.php');
} else {
echo 'There was an issue adding this item.';
};
}
}
} else {
echo "Failed";
}
Would hope this would update the database... yet it is not. I keep getting "There was an issue adding this item."
UPDATE based on our conversation below, and the code above, I think the issue is in your SQL not your PHP. I suggest adding mariadb to your question.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'INSERT INTO `inventory` ( `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (?,?,?,?)' ;
$stmt = $conn->prepare($sql)
$stmt->bind_param("ssss", $prod_name, $prod_descript, $prod_price, $img_names);
$stmt->execute()
if($stmt->affected_rows > 0) {
//header("location:https://sample.com"); #affected_rows > 0 so row was inserted
} else {
echo 'There was an issue adding this item.'; #failed to insert;
}
That should solve the issue. It is a prepared statement that will handle the issue with unescaped commas in the string as well as prevent SQL injection. Because prodId is auto increment, you don't need it in your statement, at least in MySQL you don't. The "ssss" part of the statement is assuming you are passing string values to the Db. Possible data types to be passed are:
i - integer
d - double
s - string
b - blob
See WC3Schools for more about php and prepared statements.
Related
Can I please have some help with a problem I'm having updating a mysql database with PHP.
I'm sorry to ask a question that has been asked a lot of times before, it's just driving me a bit nuts, and I've looked through similar questions but the answers don't seem to help with my problem.
I'm using two files, an admin page (admin.php) to edit content with, and an update file that is meant to update the database when the submit button is pressed.
Everything seems to be working fine, the values are being posted to the update.php page (I can see them when I echo them out) but it wont update the database.
If anyone can please point me in the right direction or tell me what I'm doing wrong I'd be very grateful!
Thank you very much:)
This is my admin.php page;
<head>
<?php
/*
Check to see if the page id has been set in the url.
If it has, set it as the $pageid variable,
If it hasn't, set the $pageid variable to 1 (Home page)
*/
if (isset($_GET['pageid'])) {
$pageid = $_GET['pageid'];
}
else {
$pageid = '1';
}
//Database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "cms";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get information from the database
$sql = "SELECT title, sub_title, tab1, tab2, tab3, content FROM data WHERE id='$pageid'";
$result = $conn ->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$conn->close();
//Store database information in variables to display in the form
$title = $row["title"];
$sub_title = $row["sub_title"];
$tab1 = $row["tab1"];
$tab2 = $row["tab2"];
$tab3 = $row["tab3"];
$content = $row["content"];
}
} else {
echo "0 results";
}
?>
</head>
<body>
//basic navigation
Page 1 | Page 2 | Page 3
<form action="update.php" method="post" name="adminform">
<input type="hidden" name="pageid" value="<?php echo "$pageid";?>">
NAME:<br>
<input type="text" name="title" value="<?php echo $title;?>"><br><br>
EMAIL:<br>
<input type="text" name="sub_title" value="<?php echo $sub_title;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab1" value="<?php echo $tab1;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab2" value="<?php echo $tab2;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab3" value="<?php echo $tab3;?>"><br><br>
CONTENT:<br>
<textarea rows="4" cols="50" name="content">
<?php echo $content;?>
</textarea>
<br><br>
<input type="submit">
</form>
</body>
And this is the update.php page;
<?php
/*Values passed from the admin form, to be used as update variables*/
if (isset($_POST['adminform']))
{
$pageid = $_POST["pageid"];
$titleu = $_POST["title"];
$sub_titleu = $_POST["sub_title"];
$tab1u = $_POST["tab1"];
$tab2u = $_POST["tab2"];
$tab3u = $_POST["tab3"];
$contentu = $_POST["content"];
}
?>
<?php
if(isset($_POST['adminform']))
{
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Update the database
$sql = "UPDATE data SET title='$titleu', sub_title='$sub_titleu', tab1='$tab1u', tab2='$tab2u', tab3='$tab3u', content='$contentu' WHERE id =='$pageid'";
$result = $conn ->query($sql);
$conn->close();
}
?>
You're using == instead of = on the where clause.
On the other hand, don't pass user values to the query without validation and sanitization if you don't want to be vulnerable to sql injection attacks.
$sql = "UPDATE data SET title='" . $conn->real_escape_string($titleu) . "', sub_title='" . $conn->real_escape_string($sub_titleu) . "', tab1='" . $conn->real_escape_string($tab1u) . "', tab2='" . $conn->real_escape_string($tab2u) . "', tab3='" . $conn->real_escape_string($tab3u) . "', content='" . $conn->real_escape_string($contentu) . "' WHERE id = " . (int)$pageid;
This will work, but is not very elegant solution. You may use prepared statements instead, to pass the correct types and prevent sql injection.
Check your DB Connections and test whether you are connected to DB or not.
Change your query as below
$sql = "UPDATE data SET title='".$titleu."', sub_title='".$sub_titleu."', tab1='".$tab1u."', tab2='".$tab2u."', tab3='".$tab3u."', content='".$contentu."' WHERE id ='$pageid'";
i have a simple form in html where user selects and ID from the table on the website (required data) and then he can / or not change 2 fields. First is a dropdown list of 2 values (strings), and the second is number of open spots!
So if a user leaves both fields empty and click send by mistake nothing should happen. If a user only changes one of the fields only that one should change!
I have checked every forum and almost all posts in here and i still cannot get it to work.
<form action="viv_settings_tecaji.php" method="post">
Datum termina (izberi ID):
<input type="number" name="ID" required><br><br>
<!--Sprememba tega datuma (če ne želiš spremenit pusti prazno):
<input type="date" name="nov_datum"><br><br>-->
Sprememba statusa (če želiš da ostane isto vpiši trenutni status!:
<select name="STATUS">
<option></option>
<option value="zaprt">Zaprt</option>
<option value="odprt">Odprt</option>
</select><br><br>
Sprememba števila odprtih mest
<input type="number" name="st_odprtih_mest"><br><br>
<input type="submit">
</form><br>
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "viverius_education";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if (empty($update_status) AND empty($update_status)){
header('Location: viv_settings_tecaji_main.php'); exit;
}
else{
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF('$update_status'='',STATUS,'$update_status'),
ST_ODPRTIH_MEST = IF('$update_st_odprtih_mest'='',STATUS,'$update_st_odprtih_mest'),
WHERE ID_TECAJA = $update_ID";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
header('Location: viv_settings_tecaji_main.php'); exit;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>
A decent form example would be like the following
<form action='' method='post'>
<input type='text' name='field1' required>
<select name='fieldSelect'>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<input type='submit' name='send'>
</form>
then the PHP would be like
<?php
if(isset($_POST['send'] && (!empty($_POST['field1']) || !empty($_POST['fieldSelect']))){
$field1 = $_POST['field1'];
$fieldSelect = $_POST['fieldSelect'];
//YOUR SQL CODE
} else {
echo "Please Insert Some Data";
}
?>
In brief:
Give your Submit button a name
Check if the submit button is clicked or not by if(isset($_POST['submit-button-name'])){}
define your form's $_POST variables with names.
Continue with SQL.
There are a couple of ways you can avoid inserting "empty" records in your database. It depends if you want to do it in the client-side (before the form submits) or server-side (when the form is submitted to the server).
I'll show you how to do it server-side, since you posted your php script.
In viv_settings_tecaji.php
...
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if($update_status == "" || $update_st_odprtih_mest == "" || $update_ID == ""){
die("One of the form fields was empty");
}
...
That would kill your script if any of the form fields was empty. Potentially, you could check for null or use PHP's empty() function.
I hope this helps!
So i manege to get it to work using the following code. So for the part if user leaves both field empty i will put together a script for at least 1 to be required.
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF(LENGTH('$update_status')=0, STATUS, '$update_status'),
ST_ODPRTIH_MEST = IF(LENGTH('$update_st_odprtih_mest')=0, ST_ODPRTIH_MEST, '$update_st_odprtih_mest')
WHERE ID_TECAJA = $update_ID";
PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
XML Codes
I have got a item list xml file for a game server, and I need to insert item names, id's and type of the item into a mysql server. I have provided 4 examples of situations, first has isstaffitem="true", second has iscashitem="true" third iscashitem="false" and fourth has nothing regarding item type. Now what I need is to read the id="string", name="string" and type of the item and insert into database. If it's staff item, set type as staff, if cash item set type to cash and set regular if something else.
How can I do that php ? I am trying with $xml = simplexml_load_string($_POST['zitem']); but can't get it work..
Here's some example code. I created a simple HTML-form, with a textarea to input the XML-code. After hitting "Submit", the PHP-script is triggered (server method = post). Connect to your database (example from w3schools). Parse the XML-string as a DomDocument (gives you more options then simple_xml). Insert each item in your xml into MySQL.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Make connection to database first
// example from http://www.w3schools.com/php/php_mysql_insert.asp
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Use DomDocument (more options / flexibility)
$doc = new DOMDocument();
$doc->loadXML($_POST['zitem']);
$items = $dom->getElementsByTagName('ITEM');
foreach ($items as $item) {
// The attributed in the XML item "ITEM", can be retrieved by using $item->getAttribute('nameofattribute')
$id = $item->getAttribute('id');
$name = $item->getAttribute('name');
$mesh_name = $item->getAttribute('mesh_name');
// Some logic, see for yourself.
$cashitem = false;
if ($item->getAttribute('iscashitem') == true) {
$cashitem = true;
}
$staffitem = false;
if ($item->getAttribute('isstaffitem') == true) {
$staffitem = true;
}
// Insert the item from XML into MySQL-table
$sql = "
INSERT INTO Items
(id, name, mesh_name, cashitem, staffitem)
VALUES (
'" . $mysqli->real_escape_string($id) . "',
'" . $mysqli->real_escape_string($name) . "',
'" . $mysqli->real_escape_string($mesh_name) . "',
'somevaluehere',
'somevaluehere'
)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
}
?>
<form method="post">
<textarea name="zitem"></textarea>
<input type="submit" value="Submit your XML file" />
</form>
Good luck!
I'm trying to create multiple HTML inserts in the same form so I can quickly insert multiple lines into my database to save time. However I'm not really sure how to process this.
<form action="admin1.php" method="post">
<?php
function multiform($x){
for ($x = 0; $x < 3; $x++){
echo 'Episode: <input type="number" name="Episode[]">
Date: <input type="date" name="Date[]">
Guest: <input type="text" name="Guest[]">
Type: <input type="text" name="Type[]">
Youtube:<input type="text" name="Youtube[]"> MP3: <input type="text" name="MP3[]"> iTunes:<input type="text" name="Itunes[]"><br/><br/>';
}
}
multiform(0);
?>
<input type="submit" value="Submit Form" name="submitForm">
</form>
This is what I tried to use:
$con = mysqli_connect("server","root","","database");
function multiformpost($x) {
for ($x = 0; $x < 3; $x++) {
$Episode = $_POST['Episode'][$x];
$Date = $_POST['Date'][$x];
$Guest = $_POST['Guest'][$x];
$Type = $_POST['Type'][$x];
$Youtube = $_POST['Youtube'][$x];
$MP3 = $_POST['MP3'][$x];
$Itunes = $_POST['Itunes'][$x];
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}')";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
if (!mysqli_query($con, $sql)) {
die ('Error: ' . mysqli_error($con));
}
echo "Added to database";
}
}
multiformpost(0);
mysqli_close($con);
Which simply returns a blank screen.. I know it's wrong but I'm not entirely sure why.
You need to be building up the VALUES section of your SQL in a loop and then executing a single query. So something like this:
$con = mysqli_connect("","","","");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
multiformpost($con);
mysqli_close($con);
function multiformpost($db) {
if(empty($db) {
throw new Exception('You need to pass a valid mysqli connection to this method');
}
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ";
$size = count($_POST['Episode']);
for ($x = 0; $x < $size; $x++) {
$Episode = mysqli_real_escape_string($db,$_POST['Episode'][$x]);
$Date = mysqli_real_escape_string($db,$_POST['Date'][$x]);
$Guest = mysqli_real_escape_string($db,$_POST['Guest'][$x]);
$Type = mysqli_real_escape_string($db,$_POST['Type'][$x]);
$Youtube = mysqli_real_escape_string($db,$_POST['Youtube'][$x]);
$MP3 = mysqli_real_escape_string($db,$_POST['MP3'][$x]);
$Itunes = mysqli_real_escape_string($db,$_POST['Itunes'][$x]);
$sql .= "('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}'),";
}
$sql = rtrim($sql,',');
if (!mysqli_query($db, $sql)) {
die ('Error: ' . mysqli_error($db));
}
echo "Added to database";
}
Note that I also made the following changes which I also suggest:
I pass in DB connection to the function. I have no idea what your original parameter was being used for, since you can detect the array size of the POST arrays directly in the function. You would be even better served moving to object-oriented mysqli usage (as you could then verify an instantiate mysqli object was passed to the function), but I didn't make that change here.
I differentiated the use of $con (for global scope) and $db (for local sope in function) so that you do not confuse the two. Previously, your code referenced $con inside function scope without declaring global so that variable would not have even been available. This dependency injection approach is highly recommended as opposed to using global.
I moved DB connection error checking outside the function
I added string escaping to mitigate against SQL injection.
I moved all your global script elements together, as functions typically should not be inserted in the middle of procedural code like you have done, as that make the code more difficult to follow.