Posting drop down menu value to mysql cell - php

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);

Related

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.

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

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

Categories