PHP not Reading <select> name for MySQL Update - php

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.

Related

string(49) "select * from php mysql error

I'm in the process of making a web page that's meant to display data that's within a database. The database is stored in MySQL and I'm making the web page in PHP. The PHP code that I have is
<form action="list_projects.php" method="post">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="partNo">Part Number</option>
<option value="pname">Part Name</option>
<option value="color">Part Colour</option>
<option value="weight">Part Weight</option>
<option value="city">City</option>
</select>
<br />
<p>Enter Search Term: </p>
<br />
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * from project where ".$searchtype." like '%".$searchterm."%'";
var_dump($query);
$result = mysqli_query($link,$query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Part Number: ";
echo htmlspecialchars(stripslashes($row['partNo']));
echo "</strong><br />Part Name: ";
echo stripslashes($row['pname']);
echo "<br />Part Colour: ";
echo stripslashes($row['color']);
echo "<br />Part Weight: ";
echo stripslashes($row['weight']);
echo "<br />City";
echo stripcslashes($row['city']);
echo "</p>";
}
mysqli_free_result($result);
mysqli_close($link);
?>
but when I run it, I get string(49) "select * from project where projectNo like '%J1%'" Number of projects found: This PHP script is meant to load different projects that's within the database and in a welcome.php script that calls this script connects to the database and it does connect to it correctly.
Looks like you've var dumped the wrong variable. You could try this instead:
$query = "SELECT * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error found: ".mysqli_error($link)); // If there's an error, it should show here.
Because it's painful, I want to rewrite your code and show you how you should be doing this:
Please note that at the top of your page is a reference to an include file in which you would set your database variable ($link).
<?php
//include "../../reference/to/mysql/login.php";
/***
* The below code block should be in your include file referenced above
***/
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
/***
* End connection block
***/
/***
* Your data is POSTed so it can not be trusted and must at the
* very least be escaped using the below functions.
***/
$searchtype=mysqli_real_escape_String($link,$_POST['searchtype']);
$searchterm=mysqli_real_escape_String($link,$_POST['searchterm']);
$searchterm=trim($searchterm);
/***
* Because your $searchtype is a column reference you need to ensure
* it fits the allowed characters criteria for MySQL columns
***/
$searchtype = preg_replace("/[a-z0-9_]/i","",$searchtype);
Please read the MySQL manual about the allowed characters to use in column names. $ is also allowed but I'm removing that from here because you really should not be using that symbol as a column name character.
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * FROM project WHERE ".$searchtype." LIKE '%".$searchterm."%'";
$result = mysqli_query($link,$query) or die("Line ".__LINE__." Error: ".mysqli_error($link));
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$i++;
echo "<p><strong>".$i.". Part Number: ";
echo htmlspecialchars($row['partNo']);
echo "</strong><br />Part Name: ";
echo htmlspecialchars($row['pname']);
echo "<br />Part Colour: ";
echo htmlspecialchars($row['color']);
echo "<br />Part Weight: ";
echo htmlspecialchars($row['weight']);
echo "<br />City ";
echo htmlspecialchars($row['city']);
echo "</p>";
}
?>
Hopefully you can see here that I have replaced your for loop with a while loop that does the same thing, taking each row from the database one at a time and outputting it as an array with identifier $row .
I have also used mysqli_fetch_array instead of your fetch_assoc.
I have corrected the spelling mistake in your stripslashes function, but also replaced stripslashes with htmlspecialchars because stripslashes is an old and almost useless renegade function that should not be used with even remotely modern Database interfacing
Your issue is also that this page coded here has not had $link declared for it, the $link idenitifier needs to be set at the top of every page that wants to connect to the database. You need to remember that PHP does not remember standard variables across pages so just because you setup $link in welcome.php does NOT mean that it is known in this page here.
Use or die (mysqli_error($link)); appended to the end of your queries to feedback to you what errors occur.
You must also get into the habit of using PHP Error Reporting to make any headway in solving your own issues.
$link is usually set up in a PHP include file that you simply call at the top of every PHP page that requires it.
IF needed, details about how to connect to MySQLi.

PHP MYSQL query not receiving data from $_POST for update

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...

sql php results and search

I have a problem, small to others, but huge to me. I have been working on a project since March 15 of this year. I am not a web designer but this is just a hobby of mine.
My problems are:
When I call this program for data, I receive records but it only works if I search for the full postcode
(EX 1: n = no results EX 2: nn12ab = 5 results displayed )
I have to arrange the results in some order
(my results = abcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ababcdabcdabcdabcdnn12ab,
the way I am trying to get them its
first name / last name / email / postcode.
I had checked in w3schools and all other mode but still I am asking this. :(
I am fully aware its no hack protected , I just want to make it work.
any idea where I need to place whatever works ?
TXT IN ADVANCE!
HTML search
<form method="post" action="search.php">
<center>
<h1>My Search Engine</h1>
<input type="text" value="Search..." name="query" />
<input type="submit" value="Find" name="list" />
</center>
</form>
PHP SEARCH and display CODE
<?php
$servername = "localhost";
$username = "abcd";
$password = "******";
$dbname = "abcd";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM wfuk";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><td><tr><th>ID</th></td></tr>
<th>Name</th></td></tr>
<th>postcode</th</td>></tr>
<th>trade</th></td></tr>
<th>telephone</th></td></tr>
<th>comments</th></td></tr></table>
";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table><tr><td>"
.$row["id"].
"</td><td>"
.$row["first_name"]
.$row["last_name"].
"</td></tr>".
"<tr><td>"
.$row["post_code"].
"</td></tr>".
"<tr><td>"
.$row["trade"].
"</td></tr>".
"<tr><td>"
.$row["telephone"].
"</td></tr>".
"<tr><td>"
.$row["comments"].
"</td></tr></table>"
;
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Substitute this line:
$sql = "SELECT * FROM wfuk";
by
$sql = "SELECT * FROM wfuk where name like " . $_POST["query"] . " order by first_name, last_name, email, postcode";
I'm assuming that the columns in table wfuk have the names you said. If not, change them by the column names.
This is not the best way to do a search, because it open the possibility for SQL-injection attacks. But at your current level of knowledge you probably aren't ready for other solution.
Later please educate yourself on better prattices on this kind of operation.
Nothing to worry about, just basic confusions .
Answer of first question:
Dont use = sign in query like this :
Select * from table where postcode='.$variable.'
Use like clause this :
Select * from table where postcode like '%.$variable.%'
Answer for Second question:
Place border for your table :
<table border="1">
a few things here
Use some good tutorials, don't trust on w3school (some people call
it w3fool)
Never User Select * from table, rather specify column names
something like Select firstname, lastname from table
if you want search based on integer, user = sign e.g where rollunme=134
if you want to search some text/ character field , use LIKE operator
eg firstname LIKE %zaffar%
these are basic tips which should help you...
PS
question edited, but these tips should still apply as they are very generic in nature and should help you
yes it work unfortunately not whit this code, but from hear i lear the pice that i was missing THX ALL .
CODE I HAVE USE
<?php
//load database connection
$host = "localhost";
$user = "change my";
$password = "change my";
$database_name = "chage my database name";
$pdo = new PDO("mysql:host=$host;dbname=$database_name", $user, $password, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
// Search from MySQL database table
$search=$_POST['search'];
$query = $pdo->prepare("select * from change_table_name where change_title LIKE '%$search%' OR change_author LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Title_Books</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Change_Author</td>
<td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">change_Price</td></tr>";
while ($results = $query->fetch()) {
// if need to multiply check clousley <tr> and </td> make shure they are on the right order
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Chage_title'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['Change_author'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
// if not needit delete "$". from bellow
echo "$".$results['change_price'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
?>
<html>
<head>
<title> How To Create A Database Search With MySQL & PHP Script | Tutorial.World.Edu </title>
</head>
<body>
<form action="search-database.php" method="post">
Search: <input type="text" name="search" placeholder=" Search here ... "/>
<input type="submit" value="Submit" />
</form>
<p>PHP MySQL Database Search by Tutorial.World.Edu</p>
</body>
</html>
i found a different code i will post it for future references but you guys let me understand the thinks i could not understand

Passing variable from input box to PHP script that calls to SQL Server

I'm having some issues with passing information from a form to a PHP script which then requests data from MySQL.
I get get data to return as long as I hard code the request; however, I'm trying to do it so when a user selects an option from the drop-down list to have it the runs the selected query. This is what I have in my form.
<form action="FETCH.PHP" method="POST" enctype="multipart/form-data">
<select name="mySelect">
<option value="South Yorkshire">South Yorkshire</option>
<option value="West Midlands">West Midlands</option>
</select>
<input type="submit" value="Go">
</form>
and this is what I have in my PHP script:
<?php
$con=mysqli_connect("*******","*******","*******","*******");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$selectedOption = $_POST["mySelect"];
$result = mysqli_query($con,"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$_POST'");
echo "<div id=Results>";
while($row = mysqli_fetch_array($result))
{
echo "<div class=ClubName>";
echo $row['EstName'];
echo "<div class=Location>";
echo $row['EstAddress2'];
echo "<br>";
}
echo date("Y") . " " ."Search is Powered by PHP.";
mysqli_close($con);
?>
I know there's something wrong here but I don't know what. This is the first time I have attempted anything with MySQL and PHP.
The current script does not give any errors but doesn't bring back any results. Any ideas?
Here in lies the problem:
$result = mysqli_query($con,
"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$_POST'");
Change that line to:
$result = mysqli_query($con,
"SELECT * FROM `SouthYorkshire` WHERE `EstProv` ='$selectedOption'");
Update
You should bind params to secure your script like this:
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption))); // pattern based on your html select options
OR...
Do it the Object Orientated way: http://php.net/manual/en/mysqli.prepare.php
WHERE `EstProv` ='$selectedOption'
In your SQL, you put the whole $_POST in, and for displaying the results, there is no close div tag.

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