Form not displaying in PHP [duplicate] - php

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.

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.

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

MySQL erase a row based on a populated combobox value

I'm trying to delete a row in mysql based on the selection I make in a combox, I know this is deprecated but it's just for personal use. By the way
I have something like this:
<form method="get" action="">
<?
require ('link.php');
mysql_select_db('proesi',$link) or die(mysql_error());
$rs = mysql_query("SELECT * FROM curso") or die(mysql_error());
echo "<select name='combo'>";
while($row2 = mysql_fetch_array($rs)){
echo "<option value='".$row2["id"]."'>".$row2["curso"]."</option>";
}
echo "</select>";
?>
<input type="submit" name="borrar" value="ELIMINAR" />
</form>
<?
$combos = $_get['combo'];
if (isset ($_post['borrar'])){
print $combos;
require ('link.php');
mysql_select_db('proesi',$link) or die(mysql_error());
mysql_query("DELETE FROM curso WHERE curso= //here i need to get the value, i'm trying to use the "id" field since it is unique// ") or die (mysql_error());
mysql_close($link);
}
?>
the select has a name. When the form is submitted, you can get it's value with $_GET['combo']
Then, in your sql,
$selected_id = $_GET['combo']; //sanitize this!!!
mysql_query("DELETE FROM curso WHERE curso= '$selected_id' ") or die (mysql_error());
of course you have to make sure the value entered into the sql is sanitized and secure from sql injections, but since you are learning, you will get to it later.

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.

Form get's resent on refresh

Form get's resent on refresh, I had read about header("Location:my_page.php") unset($_POST), but I'm not sure where to place it.
This is our script, it works as need it, but it keeps re-sending on page refresh (Chrome browser alerts over and over), can some one fix the code and explain to my like 2 years old child.
<form action='thi_very_same_page.php' method='post'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_POST['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_POST['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
}
If you mean that the form data gets submitted again upon refresh, check this method
http://www.andypemberton.com/engineering/the-post-redirect-get-pattern/
You set your header to header('HTTP/1.1 303 See Other');
Data wont be cached, so when page refreshes the form data wont get submitted again!
The problem is you are using the post method to submit the form values so when ever you tries to refresh the browser asks you whether to send the form information or not it is the default behavior of the browser to tackle the posted information, the alternate solution for your problem is you can use the get method like in form attribute method='get' what it does it will append all the information of form in the URL which we call the query string and in PHP code you are accessing the form values in $_POST but when using get method the form values will now appear in the $_GET method these methods are called request method and are PHP's global variables, Now when you try to refresh it will not ask you to resend information because the information now resides in the URL
<form action='thi_very_same_page.php' method='get'>
Search for Christian Movies <input type='text' name='query' id='text' />
<input type='submit' name='submit' id='search' value='Search' />
</form>
<?php
if (isset($_GET['submit']))
{
mysql_connect("localhost", "root", "toor") or die("Error connecting to database: " . mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = $_GET['query'];
$min_length = 2;
if (strlen($query) >= $min_length)
{
$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
echo "";
$result = mysql_query("SELECT *, DATE_FORMAT(lasteditdate, '%m-%d-%Y') AS lasteditdate FROM movies WHERE (`moviename` LIKE '%" . $query . "%') OR (`year` LIKE '%" . $query . "%')") or die(mysql_error());
if (mysql_num_rows($result) > 0)
{
while ($results = mysql_fetch_array($result))
{
echo "";
}
}
else
{
echo "";
}
}
else
{
echo "";
}
} ?>
Hope this is enough to explain you about the form submission one thing I will suggest you to deeply look at below
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Categories