PHP MYSQL query not receiving data from $_POST for update - php

I am trying to call and update a table row in a database using certain criteria. Currently I have the table load the data in textboxes and automatically assign NAMES of all the textboxes so that I can use them later to update.
Code to display
// 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");
$check=$_POST["scenario1"];
$qwert="SELECT * FROM izprashtane WHERE Сценарий='$check'";
$query=mysqli_query($conn,$qwert);
$sql = "SHOW COLUMNS FROM izprashtane";
$result = mysqli_query($conn,$sql);
echo "<table width=650 border=1>\n";
$counter=0;
while ($get_info = mysqli_fetch_row($query)){
echo "<tr>\n";
while($row = mysqli_fetch_array($result)){
echo "<td>" . $row['Field'] . "</td>";
}
echo "</tr>\n";
echo "<tr>\n";
$counter=0;
foreach ($get_info as $field){
$counter += 1;
echo "\t<td><input type='text' name='$counter' value='$field'></td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
$conn->close();
?>
<html>
<body>
<form action="datacizprashtane.php" method="POST">
<input type="submit" value="Промяна" >
</form>
</body>
</html>
This loads the table row in a table with editable textboxes and it assigns names from 0-to however I need. Then I got the code to update the table. It is just experimental so I got only 2 textboxes and I'll add the rest once I get it going.
Code to update
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE izprashtane SET НаселеноМясто='$_POST[2]',Тримесичие='$_POST[3]' WHERE Сценарий='$_POST[6]'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
$conn->close();
At this point it gives me:
Error updating record: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '�аселеноМясто='',Тримес' at line 1.
I have tried to use '".$_POST[3]."' but then it doesn't even give me the error. Any ideas of what I am doing wrong?

I think your problem is that the <input...> fields in your HTML are not inside a <form....> tag.
If fields are not placed inside a <form> they are not sent when the submit button is pressed. In fact they are not even inside the page <body>
Currently only the submit button is inside your <form> tag, which is why the submit is being actioned but no data is being passed and you are not checking the fields actually exist before using them.

Give the following a go with prepared statements:
$sql = "UPDATE izprashtane SET НаселеноМясто=?,Тримесичие=? WHERE Сценарий=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_bind_param($stmt, "sss", $_POST['2'], $_POST['3'], $_POST['6']);
mysqli_execute($stmt);
Also, your code is a bit of a mess, make sure to escape strings using prepared statements or mysqli_escape_string to avoid SQL Injections.
EDIT:
Also, add
mysqli_set_charset($conn,"utf8");
After the second database connection while also making sure that your inputs are all in your form.

you must place all the form fields in between form tags(<form>...</form>)
ex:
<form action="datacizprashtane.php" method="POST">
<?php
//write your php code here.
?>
<input type="submit" value="Промяна" >
</form>
i hope it will help you...

Related

Cannot get my PHP code to remove row in mysql

I am currently trying to make it so my PHP code can remove appointment records in mysql. I have been trying for quite some time without any luck.
Here is my code where you would select which appointment to remove. All of the appointments display correctly in a dropdown menu on this page.
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
$sql2 = "SELECT a.appointmentID
FROM AppointmentDetail AS a, Customer AS c
WHERE a.customerID=c.customerID
AND a.appointmentStatus<>'completed'
AND emailAddress = '".$_SESSION['username']."';";
$result2 = mysqli_query($db, $sql2);
echo "<h2 class='ArticleHeader1'>Cancel one of your Upcoming Appointments</h2>";
echo "<form action='Example.php' method='post'>";
echo "<p> Select an AppointmentID from the list below </p>";
echo "<select type='text' name='appointmentCancel' required>";
while($row2 = mysqli_fetch_row($result2))
{foreach($row2 as $cell2)
echo "<option value='".$cell2."'>$cell2</option>";}
echo "</select>";
echo "<input type='submit' name='formDelete' value='Cancel Appointment' class='button'/>";
echo "</form>";
mysqli_close($db);
?>
Here is the Example.php form that I would submit to where I always get the "Sorry! There has been an error in canceling your appointment. Please contact your Administrator"
<?php
session_start();
$db = mysqli_connect("localhost", "user", "pass", "database");
if (!$db) { die("Connection failed: " . mysqli_connect_error()); }
if(isset($_POST['formDelete']))
{
$appointmentDelete = mysqli_real_escape_string($db, $_POST['appointmentCancel']);
$del_val = "DELETE FROM AppointmentDetail
WHERE appointmentID='".$appointmentDelete;."';";
$saved = mysqli_query($db, $del_val);
if($saved) {
echo "Your Appointment Has Been Successfully Cancelled!";
} else {
echo "Sorry! There has been an error in canceling your appointment.
Please contact your Administrator";
}
}
mysqli_close($db);
?>
I have tried using different SQL queries to remove records based on different fields other than appointmentID with no luck. But appointmentID is the simplest so since none of the fields are working, I must be doing something wrong.
I have also tried messing around with the quotes around $appointmentDelete and a few other variables with no luck.
I am pretty new to PHP and SQL so I really am just looking to get this basic functionality down.
I have cut out a lot of the additional code on my first PHP page to only include what I believe to be relevant.
There's an concatenation error in your delete query. Change it as bellow,
$del_val = "DELETE FROM AppointmentDetail WHERE appointmentID=$appointmentDelete";
Please refer PHP - concatenate or directly insert variables in string for more details about concatenation.

Populate a dropdown menu from a MySQL database in a WordPress page

I have a WordPress site in which I want to show to the user a list of cities to choose from and show in a Google map.
I have made a HTML dropdown menu which I want to populate with cities which are retrieved from a MySQL table named Map_of_resellers.
Problem is, the dropdown box is shown in the page but it's empty (it has no entries).
The code I use shows me if the connection to the database is successful and also if the db query is succesfull so these are not the issues.
If you wonder what the [insert_php] and [/insert_php] tags are, they are shortcodes to allow PHP in a WordPress page since it's not supported natively.
They are used by a WordPress plugin named Insert PHP which i installed for this purpose.
Here is my PHP code:
[insert_php]
$servername = "sql102.*******.com";
$username = "b3_*******";
$password = "********";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db('b3_**********');
$sql="SELECT City FROM Map_of_resellers";
$result=mysqli_query($sql);
if($result === FALSE)
{
die("Query failed: " . mysqli_error());
}
[/insert_php]
<form name="Cities" method="post" >
[insert_php]
echo "<select name='City'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<option value='" . $row['City'] ."'>" .
$row['City']."</option>";
}
echo "</select>";
[/insert_php]
</form>
Any help would be greatly appreciated!
Looking at the source code for the plugin you mentioned, it uses eval to parse the PHP code. New variables created inside an evaluated script won't be in scope when the evaluation has ended. So $results won't be accessible in your second code block.
Replacing the code like below should keep $results in scope and fix the issue:
[/insert_php]
<form name="Cities" method="post" >
[insert_php]
to
echo '<form name="Cities" method="post" >';

PHP not Reading <select> name for MySQL Update

I'm working on a fantasy football database just for fun and I have made some progress with a PHP page but am stuck with an issue in getting data from my html data to be read by my php update script (update.php)
Here's my code for the form:
$servername = "localhost";
$username = "root";
$password = "nottelling";
$dbname = "Football";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sqlqb = "SELECT Name_Team_Position FROM Football.2016_Players_QB;";
$resultqb = $conn->query($sqlqb);
echo " <form method=\"post\" action=\"update.php\"> <br> Enter Passcode:";
echo " <input name = \"Passcode\" type = \"text\"> </input> <br><br> ";
echo " Pick your QB: <select name='QB'> </option> "; // list box select command
foreach ($conn->query($sqlqb) as $row){
// Array or records stored in $row
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
/* Option values are added by looping through the array */
}
echo " </select> ";// Closing of list box
echo " <br><br> <input type=\"submit\" value=\"Submit\"> </input> ";
echo " </form> ";
$conn->close();
?>
And here's update.php
$servername = "localhost";
$username = "root";
$password = "nottelling";
$dbname = "Football";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value1 = $_POST['Passcode'];
$value2 = $_POST['QB'];
$sql = "UPDATE Football.PlayerTeams SET QB = '$value2' WHERE Password = '$value1';";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
My problem as concisely as I can put it:
This script is definitely connecting properly to the DB and executing the update query successfully. The problem is that $value1 is not receiving any value from the html form. If I insert the string "test" into the row corresponding with the passcode, and then I use the form this code producing, it runs successfully but then when I check the db "test" is gone and instead its just blank - "". Can someone help me figure out what I'm doing wrong in trying to get the drop-down value to my action script?
This is wrong:
echo " Pick your QB: <select name='QB'> </option> ";
The </option> are wrong placed
Replace: echo " Pick your QB: <select name='QB'>";
Replace: echo " <br><br> <input type=\"submit\" value=\"Submit\">";
The $row['id'] is the value that you become in your QB if your POST.
echo " <option value='TheValueYouNeededHere'>Display Name</option> ";
And for POST use filter_input — Gets a specific external variable by name and optionally filters it:
filter_input(INPUT_POST, QB, filter);
The filters you find here: http://php.net/manual/de/filter.filters.php
Copy from User:
$sql = "UPDATE Football.PlayerTeams SET QB = '".$value2."' WHERE Password = '".$value1."'";
Is more beautiful for the eyes, you must not use ".$Value." In php works without i mean, correct me when i'm wrong
Security:
Your MySQL query can easy injected. And your passwort is Visible.
It gives multiple choices to avoid this.
MySQL injecton:
You can replace some char's. (Char are single character)
The most dangerous things you can replace with other characters. Filter Input have nice filters like htmlspecialchars. I Think you find much things if you search little :)
Password:
First make <input type='password'>.
Then Hash your password or pick MD5 or something to make it "unreadeble". You can set it on MySQL. With PHP u build the "secure" value.
MD5 is not the best option. Its only easy to implement for beginning.
Hope this helps :)
Because you have nothing in you value attribute of option. Try to inspect options tag you will see your value =$row[id] which is senseless try to use this
echo " <option value='".$row['id']."'>$row['Name_Team_Position']</option> ";
or
foreach ($conn->query($sqlqb) as $row)
{ ?>
<option value=<?php echo $row[id];?>><?php echo $row['Name_Team_Position'];?></option>
<?php } ?>
Please try the following and let me know.
echo " Pick your QB: <select name='QB'> </option> "; // list box select command
foreach ($conn->query($sqlqb) as $row){
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
into
echo " Pick your QB: "; // list box select command
while($row = $resultqb->fetch_assoc()){
echo " ".$row['Name_Team_Position']." ";
$sql = "UPDATE Football.PlayerTeams SET QB = '$value2' WHERE Password = '$value1';";
Into
$sql = "UPDATE Football.PlayerTeams SET QB = '".$value2."' WHERE Password = '".$value1."'";
Try replacing
foreach ($conn->query($sqlqb) as $row)
{ // Array or records stored in $row
echo " <option value=$row[id]>$row[Name_Team_Position]</option> ";
/* Option values are added by looping through the array */
with
while($row = $resultqb->fetch_assoc())
{ // Array or records stored in $row
echo " <option value=$row['id']>$row['Name_Team_Position']</option> ";
/* Option values are added by looping through the array */
Edit
Array index should be in strings.

Creating a drop down list but the php won't work [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 6 years ago.
So there's a lot of people helping to create a drop down list in html and populating it with their database. I'm trying to do this and I found some php code to do it but it just doesn't work. I understand php, sql and html but just not how they combine together. What seems to be the problem is that after the first echo, the rest of the code is just outputted as code to the page and it doesn't do anything. This is the code:
<html>
<body>
<?php
mysql_connect('localhost', 'root', 'password');
mysql_select_db('FoodMatching');
$sql = "SELECT IngID, IngName FROM Ingredient Characteristics";
$result = mysql_query($sql);
echo "<select name='Ingredient Name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['IngName'] ."'>" . $row['IngName'] ."</option>";
}
echo "</select>";
?>
</body>
</html>
And what I see on the webpage is:
"; while ($row = mysql_fetch_array($result)) { echo "
" . $row['IngName'] ."
"; } echo ""; ?>
There's no errors/warnings that pop up so I don't know what the problem is. Thank you if you can help :)
As mentioned you should look to use PDO's to talk to the DB.
If you get the list before the html is output then you can have much cleaner and easier to understand code
See if the below makes sense, you might need to make a few modifications as its untested.
There are some comments about your mySql, ensure that results are being returned when you run the query.
<?php
define( "DB_DSN", "mysql:host=localhost;dbname=foo");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "password" );
// define the empty array to be filled from db
$aIngredeintCats = array();
// any other php tasks that dont needthe ingcats
// store sql
$sSQL = "SELECT IngID, IngName FROM IngredientCharacterisitics";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// if required securely bind any user input in the query
// $st->bindValue(":IngID", $sIngName, PDO::PARAM_STR);
// execute the connection
$st->execute();
/* this will show if a result has been returned from the db.
echo "<pre>";
var_dump($st->fetch());
echo "</pre>";
*/
// while myslq has rows loop over them and store
while($row = $st->fetch() ){
// use the IngID from db as the array key
// also strip any tags from the output. other sanatisation should be done
$aIngredeintCats[$row['IngID']] = strip_tags($row['IngName']);
}
// any other php tasks if they need the list of cats
?>
<html>
<body>
<form method='post' action='/'>
<?php
// if there are results stored create the select and loop over
if(!empty($aIngredeintCats)){
echo "<select name='IngredientName'>";
echo "<option value='' default>default</option>"
foreach ($aIngredeintCats as $iIngID => $sIngName) {
echo "<option value='".$sIngName."' >".$sIngName."</option>";
}
echo "</select>";
}else{
echo "<p>No results avaliable!</p>";
}
?>
</form>
</body>
</html>

Posting drop down menu value to mysql cell

Alrighty, so i'm quite a beginner when it comes to PHP and MySQL programming so the problem might be quite noobish but anyway here's my situation. I've got a content page with a dropdown menu that should give me a $_POST value (the options are taken from a database column): here's the code for that
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" />
<?php
include("../panel/config.php");
$db = mysqli_connect($server, $username, $password, $database);
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established " .
mysqli_connect_error($db) . "</p>");
}
$query = "SELECT username FROM users WHERE email = '1' ORDER BY username ASC";
$result = mysqli_query($db,$query);
if (!$result) {
echo("Error, the query could not be executed: " .
mysqli_error($db) . "</p>");
mysqli_close($db);
}
echo "
<form action='myscript' method='post'>
<select name='test'>
<option value = 'none' selected = 'selected' >
`Select a DJ:` </option>";
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="' . $row['username'] . '">' . $row['username']. '</option>';
}
echo"
<input type='submit' value='submit' name='submit'>
</select>
</form> ";
?>
Quite a bit of code for such a small function i know. Anyway the drop down menu gets its options from a database column and that works fine, now when i press the submit button, it runs another php page that's coded like this:
<link href="../css/pagestyle.css" rel="stylesheet" type="text/css" /><html>
<?php
include("../panel/config.php");
$con = mysqli_connect($server, $username, $password, $database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['test'];
$order = "UPDATE `habboxli_system`.`users` SET `points` = points+1 WHERE `users`.`username` ='$id'";
mysql_query($order);
echo "name is $id";
mysqli_close($con);
echo "Vote posted!";
?>
This code should take the value that was chosen in the drop down menu and use it to update a specific cell in the database, i signed it to a variable called $id just for testing purposes but the value seems to be blank, so from that i presume that the drop down menu didn't return a value when it navigated from the original page (www.mywebsite.com/#/option.php) to the myscript.php page (www.mywebsite.com/#/myscript.php). Any help on how to get this to work would be much appreciated.
As was said in the comments, you are using the mysql_query function mixed in with the mysqli functions.
I got the code to work for me by changing
mysql_query($order);
To:
mysqli_query($con, $order);
You can also debug what was passed to the script by simply printing the $_POST array:
print_r($_POST);

Categories