I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.
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 this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">
I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php
I am new to web design, and I'm using a very simple ajax method to get the id of a product from a database. Being so new to backend stuff, I was wondering if anyone wouldn't mind teaching me a little about php security.
My first area in question is the post method and the method in which i get the data for the post method.
function setupc(upc) {
var sku1 = $("#option1 option:selected").data('sku');
var sku2 = $("#option2 option:selected").data('sku');
if (sku2 !== null) {
upc = (sku1 + sku2);
} else {
upc = (sku1);
}
$('input[name="upc"]').val(upc);
$.post('getproduct.php', {upc: upc}, function(data){
$('.result').html(data);
});
}
And here is the getproduct.php
<?php
require_once("config.php");
$con=mysql_connect (MySQL, $username, $password);
if (!$con) {
die("Not connected : " . mysql_error());
}
$db = mysql_select_db($database, $con);
if (!$db) {
die ("Can\'t use db : " . mysql_error());
}
$upc = "$_POST[upc]";
$sql = "SELECT * FROM products WHERE upc = '$upc'";
$result = mysql_query($sql, $con) or die(mysql_error());
$row=mysql_fetch_array($result);
?>
<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>">
<input type="text" id="price" value="<? echo $row['price']; ?>">
<?php mysql_close($con); ?>
If this is not the place to ask these kinds of questions, please let me know and I'll gladly remove it. And, maybe even point me to a place that i can.
your code doesn't prevent so-called "SQL injection"
This means that someone can call your script with sql-statements in the
$_POST['upc'] parameter
Your query would be better using mysql_real_escape_string:
$sql = "SELECT * FROM products WHERE upc = '" . mysql_real_escape_string($upc) . "'";
any sql code would be escaped and won't be executed.
EDIT: you also may google for "SQL injection" a little bit, to learn about this security matter
i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>