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.
Related
Hi I have manage to put this script together as a newbe. I have divided the script up in two parts each part works individually, but when putting it together and when I make the WHERE as a changeable value it won't work.
(the reason for the line in error everywhere/shortcode.php(15) is because its running on a php wordpress plugin, but as I say the to parts works individual)
Can someone tell me how I can pass that value
$myvalue
and open the connection in part two of the script, without getting error on the connection part. The value do get past to the varible but makes an error.
Here is the errors I get:
Warning: mysqli_query(): Couldn't fetch mysqli in /home/asports/public_html/calendar/wp-content/plugins/php-everywhere/shortcode.php(15) : eval()'d code on line 34
Warning: mysqli_error(): Couldn't fetch mysqli in /home/asports/public_html/calendar/wp-content/plugins/php-everywhere/shortcode.php(15) : eval()'d code on line 52
ERROR: Could not able to execute SELECT men_slope FROM allcourses WHERE id='3'.
Warning: mysqli_close(): Couldn't fetch mysqli in /home/asports/public_html/calendar/wp-content/plugins/php-everywhere/shortcode.php(15) : eval()'d code on line 56
// part one
<?php
require_once(
$_SERVER['DOCUMENT_ROOT'].'/calendar/courses/admin/connect.php');
?>
<form method=post>
<select name="myvalue">
<?php
// Attempt select query execution
$sql = "SELECT id, Name, color FROM allcourses";
$sql = mysqli_query($link, $sql);
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['id']."'>".$row['Name'] . " (" . $row['color'].
")" . "</option>";
}
// Close connection
mysqli_close($link);
$myvalue=$_POST['myvalue'];
$myhdc=$_POST['hdc'];
?>
</select>
<br />
<p>Handicap: </p>
<input class="tex" type="text" name="hdc"\></input>
<br />
<input type=submit>
</form>
// Part two
<?php
// Attempt select query execution
$sqll = "SELECT men_slope FROM allcourses WHERE id='$myvalue'";
if($result = mysqli_query($link, $sqll)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['men_slope'] . "</td>";
echo "</tr>";
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqll. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
The problem is that you call mysqli_close($link); in Part One. Then when you try to perform a query in Part Two, the link is closed, so you can't use it any more.
IHMO, it's usually not important to call mysqli_close(). The connection will be closed automatically when the script ends. So unless your script runs for a long time after making all its database queries, it will not be idle for very long.
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.
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.
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
So I have a page using PHP and a MySQL query. What I'm wanting to do is create basically an "edit" page that takes data from my database and uses it to show the values in various inputs. The user can then change the data in the input which will then update the corresponding MySQL table row. However, for whatever reason the page is NOT displaying the form, but rolling over to the else statement. I can verify the $_SESSION['weaponName'] is working, because it will echo the correct thing. Any ideas on why the form will not show up for me?
edit.php
<?php
session_start();
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$weaponName = $_SESSION['weaponName'];
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
if(mysqli_num_rows($query)>=1){
while($row = mysqli_fetch_array($query)) {
$creator= $row['creator'];
$weaponCategory= $row['weaponCategory'];
$weaponSubCategory= $row['weaponSubCategory'];
$costAmount= $row['costAmount'];
$costType= $row['costType'];
$damageS= $row['damageS'];
$damageM= $row['damageM'];
$critical= $row['critical'];
$rangeIncrement= $row['rangeIncrement'];
$weight= $row['weight'];
$weaponType= $row['weaponType'];
$masterwork= $row['masterwork'];
$attributes= $row['attributes'];
$specialAbilities= $row['specialAbilities'];
$additionalInfo= $row['additionalInfo'];
}
?>
<form action="weaponEditUpdate.php" method="post">
<input type="hidden" name="weaponName" value="<?php echo $weaponName;?>">
Weapon Name: <input type="text" name="weaponName" value="<?php echo $weaponName;?>">
<br>
Weapon Category: <select name="weaponCategory">
<?php while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['weaponCategory'] ."'>" . $row['weaponCategory'] ."</option>";
} ?>
</select>
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
As requested by OP (from comment conversations)
Instead of
if(mysqli_num_rows($query)>=1){
use
if(mysqli_num_rows($query) >0){
You're mixing functions
mysqli_connect("localhost","username","password","db_name");
Won't work with
mysql_query("SELECT * FROM weapons limit 1");
Try
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
And then
if($query->num_rows >= 1)
change this
$query = mysql_query("SELECT * FROM weapons limit 1");
to
$query = mysqli_query("SELECT * FROM weapons limit 1");
BUT omg all your code is mysql while you connected by mysqli !! .
You connect with mysqli, which is fine. THEN, you attempt to run queries via mysql. Those are two separate extensions. You can't mix them as they won't "communicate" with one another. Stick to mysqli.
When I add this code to my Php file
include "sql_connect.php";
$query_blog="SELECT * FROM messages";
$result_blog=mysql_query($query_blog);
$num_blog=mysql_numrows($result_blog);
mysql_close();
$sql_index_menu="0";
while ($sql_index_menu < $num) {
$msg_subject=mysql_result($result,$sql_index_menu,"subject");
$msg_id=mysql_result($result,$sql_index_menu,"id");
$msg_from=mysql_result($result,$sql_index_menu,"from");
$msg_to=mysql_result($result,$sql_index_menu,"recipient");
$msg_text=mysql_result($result,$sql_index_menu,"text");
$msg_time=mysql_result($result,$sql_index_menu,"time");
$msg_read=mysql_result($result,$sql_index_menu,"readed");
?>
<tr>
<td><?php if($msg_read == "0") {echo "<img src='/images/message.gif' width='32' height='32'>";} else {echo "<img src='/images/message.png' width='32' height='32'>";}?> <?php echo $msg_time; ?></td><td><?php echo $msg_subject; ?></td><td><?php echo $msg_from; ?></td>
</tr>
<?php
$sql_index_menu++;
}
everything work BUT, when i add this to $query_blog
$query_blog="SELECT * FROM messages WHERE recipent='$username'";
so it won't work..
I tryed to change $username with my name but it still not working.
This code is working, so I copyed it and still nothing...
include "sql_connect.php";
$query="UPDATE messages
SET readed='1'
WHERE id='$id'";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
include "sql_connect.php";
$query_blog="SELECT * FROM messages WHERE id='$id'";
$result_blog=mysql_query($query_blog);
$num_blog=mysql_numrows($result_blog);
mysql_close();
$msg_text=mysql_result($result_blog,$sql_index_blog,"text");
$msg_from=mysql_result($result_blog,$sql_index_blog,"from");
$msg_subject=mysql_result($result_blog,$sql_index_blog,"subject");
$msg_time=mysql_result($result_blog,$sql_index_blog,"time");
Can you help me?
I disabled login required to page so now you can see the page (sorry for language :D) As you can see, no error
The website
as mentioned there is a typo, you misstyped recipient, anyway - i recommend you to use mysql_error() function to debug you'r code, an example would be:
$result=mysql_query($query) or die("<b>error:</b>".mysql_error()."line:".__LINE__);
The easiest way to debug a code in PHP is using echo or print_r.
In this case, you can include echo on $query_blog after setting it and run the result in your mysql IDE (or mysql command line).
$query_blog="SELECT * FROM messages WHERE recipent='$username'";
echo $query_blog;
Also, it's not a good msyql practice using quotes on where because your code will be vulnerable to injections.
Instead, use this:
$result = sprintf("SELECT * FROM messages WHERE recipent='%s'", mysql_real_escape_string($username));
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $result
die($message);
}
If you are querying a mysql database from php and you want to use php variables in your query you have to escape them, otherwise you are passing the string '$username', not the value that is stored in $username.
Does this work for you?
$query_blog="SELECT * FROM messages WHERE recipent='" . $username . "'";
var_dump($query_blog);