I'm trying to get some data from MySQL to be displayed on a PHP webpage but no data is getting displayed.
I have the variables searchterm and searchtype declared higher up in the HTML code. The HTML code only has an option of a drop down menu and an option for the user to search.
When I run the code however, no data is displayed. All I get is: "Number of projects found:" which is where the data is meant to be displayed.
The full HTML and PHP code that I have is shown below.
<html>
<body>
<h1>Search</h1>
<form action="list_projects.php" method="POST">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="projectNo">Project Number</option>
<option value="pjname">Project Name</option>
<option value="city">Project City</option>
</select>
<br />
<p>Enter Search Term: </p>
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$hostname='mysql.uniwebsite.ac.uk';
$database='somedatabase';
$username='uniusername';
$password='unipassword';
$link = mysqli_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysqli_error());
}
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * FROM tables WHERE ".$searchtype." like '%".$searchterm."%'";
$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).". Project Number: ";
echo htmlspecialchars(stripslashes($row['projectNo']));
echo "</strong><br />Project Name: ";
echo stripslashes($row['pjname']);
echo "<br />Project City: ";
echo stripslashes($row['city']);
echo "</p>";
}
$mysqli_free_result($result);
$mysqli_close($link);
?>
</body>
</html>
The following errors are what I get when I turn error reporting on:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/list_projects.php on line 39
Number of projects found:
Notice: Undefined variable: mysqli_free_result in /home/list_projects.php on line 52
Fatal error: Function name must be a string in /home/list_projects.php on line 52
Some improved code to help you on your way, see the Change: and Homework: lines:
<html>
<body>
<h1>Search</h1>
<form action="list_projects.php" method="POST">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="projectNo">Project Number</option>
<option value="pjname">Project Name</option>
<option value="city">Project City</option>
</select>
<br />
<p>Enter Search Term: </p>
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
// Change 1: Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$hostname='mysql.uniwebsite.ac.uk';
$database='somedatabase';
$username='uniusername';
$password='unipassword';
// Change 2: Add $database
$link = mysqli_connect($hostname, $username, $password, $database);
// Change 3: Literally copy&paste error checking from mysqli_query docs page
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Homework: Check for legal values in more detail
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
// Homework: Use prepared statements to avoid sql injection
$query = "select * FROM tables WHERE ".$searchtype." like '%".$searchterm."%'";
// Change 4: Error checking
if ($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).". Project Number: ";
echo htmlspecialchars(stripslashes($row['projectNo']));
echo "</strong><br />Project Name: ";
echo stripslashes($row['pjname']);
echo "<br />Project City: ";
echo stripslashes($row['city']);
echo "</p>";
}
// Change 5.1: Remove $
mysqli_free_result($result);
} else {
printf("Error: %s\n", mysqli_error($link));
}
// Change 5.2: Remove $
mysqli_close($link);
?>
</body>
</html>
Related
I'm trying to create a simple search engine in php, in which if the user enters a keyword they can search by event name or location. Then the results to be displayed in date order. Most of the has been taken from another site, but I am trying to convert it.
Can someone explain the error below to a newbie, in simple terms and how to correct it?
/home/ubuntu/workspace/test/test.php:49: array(5) { 'eventID' => string(1) "1" 'eventName' => string(8) "Exciting" 'eventLocation' => string(7) "Stadium" 'commencing' => string(10) "2017-04-01" 'expires' => string(10) "2017-04-30" } Warning: Illegal string offset 'eventName' in /home/ubuntu/workspace/test/test.php on line 50 Call Stack: 0.0003 238624 1. {main}() /home/ubuntu/workspace/test/test.php:0 1
<?php
session_start();
//include files
include 'header/header.php';
include 'nav/navigation.php';
include 'init.php';
$expires = strtotime($_POST["expires"]);
$expires = date('Y-m-d', $expires);
$events = "";
$find = $_POST['find'];
$field = $_POST['field'];
$searching = true;
if(isset($_POST["submit"])) {
if(!empty($_POST["events"])) {
$searching = false;
}
//This is only displayed if the user submitted the form
if($searching == true)
{
echo "<h2>Results</h2><p>";
//If the user did not enter a search term, they receive an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to the database
//$result = mysqli_query($connection,$query) or exit ("Error in query:
$query. ".mysqli_error($connection));
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$mysqli = new mysqli('localhost', 'root', '', 'c3470438');
$query = "SELECT * FROM events WHERE upper(eventLocation)
LIKE'%STADIUM%'";
$result = $mysqli->query($query);
//Temporarily echo $query for debugging purposes
//echo "$query";
//exit;
//And display the results
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<br>";
foreach($row as $item) {
var_dump($row);
echo $item['eventName'];
exit();
}
exit;
//This counts the number or results. If there aren't any, it gives an
explanation
$anymatches=mysql_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br>
<br>";
}
//And reminds the user what they searched for
echo "<b>Searched For:</b> " .$find;
}
}
?>
<fieldset>
<legend><h2>Events</h2></legend>
<form name="search" method="post" action="<?=$PHP_SELF?>">
<tr> <th> <td>
<fieldset>
<legend>Find all events</legend>
<input type="radio" name="events" <?php if (isset($events) &&
$events=="all") echo "checked";?>value="all"> Display all events
</fieldset>
<fieldset>
<legend>Find events by date</legend>
<input type="date" name="date" min="<?php echo date("Y-m-d");?>"
max="2025-01-01" value="<?php echo date("Y-m-d");?>">
</fieldset>
<fieldset>
<legend>Find events by keywords</legend>
<input type="hidden" placeholder='Search by keyword'name="searching"
value="yes" />
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="eventName">Event Name</option>
<Option VALUE="eventLocation">Event Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="submit" />
</form>
</fieldset>
<button name="submit" value="submit" type="submit" class="button
expanded">Submit </button>
<button type="reset" value="Clear"class="button expanded">
Clear</button>
</fieldset>
</select> </td></tr>
<?php
//include files
include 'footer/footer.php';
?>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
</script>
</body>
Well $result->fetch_array(MYSQLI_ASSOC) returns a single row, but you are using it as if it returns all rows. So your foreach is iterating each field in the row, not each row and therefore you're trying to access an array key of a string.
Use a while like so:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['eventName'];
}
Also, you're using mysql_num_rows which is not part of mysqli. Instead use $result->num_rows.
Technically it accepts all the input but there no any error message that there is something wrong with my code. The insert is located at the bottom part of the code which is strangely not working because I tried my insert statement in the database and of course changing the variables with real values and it worked that way.
Tried this insert statement in my workbench and it worked:
INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone) VALUES ('1','Kristen','123','Kristen Crooks','Volunteer','2','2016-10-11 14:09','0','0')
Code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<center><b> Volunteer Management </b></center>
<center>
Add User
Add Skills
Assign User
</center>
</head>
<body>
<?php
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT skillName FROM skills";
$result = $conn->query($sql);
$num=mysqli_num_rows($result);
$conn->close();
?>
<form method="get">
Username: <br>
<input type="text" name="username"> <br>
Password: <br>
<input type="text" name="password"> <br>
Name: <br>
<input type="text" name="name"> <br>
Title: <br>
<input type="text" name="title"> <br> <br>
Permission:
<select id="permission" name="permission">
<option selected disabled>Choose here</option>
<option value="0">Admin</option>
<option value="1">Project Manager</option>
<option value="2">Volunteer</option>
<option value="6">Accounting Officer</option>
</select> <br><br>
Skills: <br>
<?php
$i=0;while ($row = mysqli_fetch_assoc($result)) {
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills" value="<?php echo $skillName; ?>" ><?php echo $skillName; ?><br>
<?php $i++;} ?>
<br>
<input type="submit" name="submit">
</form>
<?php
if(isset($_GET['submit']))
{
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$login = $_GET['username'];
$password = $_GET['password'];
$name = $_GET['name'];
$title = $_GET['title'];
$profil = $_GET['permission'];
$created = date('Y-m-d H:i:s');
$sql = "INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone)
VALUES ('1','$login','$password','$name','$title','$profil','$created','0','0')";
$result = $conn->query($sql) or die('Error, insert query failed');
$conn->close();
}
?>
</body>
Okay I already dissected the code and it appears that the $created = date('Y-m-d H:i:s'); is causing the error. By the time I tried not to include it in the data in the insert statement, it worked! I guess I have to get another way to get the date from the system.
Also I've checked that the reason why there is an error is because the date format is in VARCHAR and not in date and another problem is that it does not fit in the length that set. Although I want to ask why it is not detected by the server that there is an error like that
Check PHP log and mysql log, write what is there.
Put an echo before the INSERT, check if your script comes to that place.
If echo is not working- then the problem is not in INSERT
I have two forms on one page. First one take names of students according to group. Second form is used to enter marks individually. Now i want to insert their marks but failed to do this. Kindly help me regarding this. My code is:
$faculty = null; //declare vars
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_select_db('Sims', $link) or die("cannot select DB");
if(isset($_POST["faculty"]))
{
$faculty = $_POST["faculty"];
}
?>
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
<form name="theForm" method="post">
<select name="faculty" onChange="autoSubmit();">
<option value="null"></option>
<option value="computer" <?php if($faculty == 'computer') echo " selected"; ?>>Computer</option>
<option value="commerce" <?php if($faculty == 'commerce') echo " selected"; ?>>Commerce</option>
</select>
<br><br>
<?php
if($faculty =='computer')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'computer' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
if($faculty =='commerce')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'commerce' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
?>
<br><br>
</form>
<form method="post">
math <input type="text" name="urdu" />
science <input type="text" name="science" />
social <input type="text" name="social" />
submit
</form>
I have a database created with five fields
ValueA
ValueB
ValueC
ValueD
ValueE
and I am trying to make a search form that can search by each of these individual fields, e.g if the value in ValueB was "Blue", select ValueB from the dropdown then type in "Blue" to print out all the values in the row that Blue was a part of. So far, I've created an html file called "findme.html":
<html>
<head>
<title>Search</title>
</head>
<body bgcolor=#ffffff>
<h2>Search</h2>
<form name="search" method="post" action="findme2.php">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="ValueA">Value A</option>
<Option VALUE="ValueB">Value B</option>
<Option VALUE="ValueC">Value C</option>
<Option VALUE="ValueD">Value D</option>
<Option VALUE="ValueE">Value E</option>
</Select>
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
and also created a php file called "findme2.php":
<html>
<head>
<title>Searching through Database Table mytablename</title>
</head>
<body bgcolor=#ffffff>
<?php
include "config.php";
echo "<h2>Search Results:</h2><p>";
if(isset($_POST['search']))
{
$find =$_POST['find'];
}
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<p>You forgot to enter a search term!!!";
exit;
}
// Otherwise we connect to our Database
$username="xxxxxxxx";
$password="xxxxxxxx";
$database="xxxxxx_xxxxxxx";
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// We perform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$iname = mysql_query("SELECT * FROM mytablename WHERE upper($field) LIKE '%$find%'")
or die(mysql_error());
//And we display the results
while($result = mysql_fetch_array( $iname ))
{
echo "id :" .$result['ValueA'];
echo "<br> ";
echo "name :".$result['ValueB'];
echo "<br>";
echo "name :".$result['ValueC'];
echo "<br>";
echo "name :".$result['ValueD'];
echo "<br>";
echo "name :".$result['ValueE'];
echo "<br>";
echo "<br>";
}
$anymatches = mysql_num_rows($iname);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query...<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
?>
</body>
</html>
I believe my problem is with the query command, but I am not sure how to adjust the syntax. Can anyone help me?
You forgot to set your $field variable.
In your if statement, you should change it to
if(isset($_POST['search']))
{
$find =$_POST['find'];
$field =$_POST['field'];
}
It should work then.
I am having trouble getting this form to successfully submit the data to the database. I have verified that the database/table exists (schema shown below) and for some reason it's not inserting it into the database. When I try to submit sample data, it doesn't change the page and just sits there. What is going on?
<body>
<?php if($_SERVER["REQUEST_METHOD"] != "POST"){ ?>
<h1>My Favorite Foods</h1>
<form action="index.php" method="post" id="foodForm">
Name: <input type="text" name="foodname" id="nameField"></input><br />
Type: <select name="foodtype" id="typeField">
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
<option value="dairy">Dairy</option>
<option value="meat">Meat</option>
<option value="grain">Grain</option>
<option value="other">Other</option>
</select><br />
Number of Calories: <input type="text" name="foodcals" id="calsField"></input><br />
Healthy? <input type="checkbox" name="foodhealth" value="healthy" id="healthyField"></input><br />
Additional Notes:<br />
<textarea name="foodnotes" id="notesField"></textarea><br />
<input type="submit" value="Add" onclick="validateForm();return false;"></input>
</form>
<?php }else{ ?>
<!-- form handling and output printing stuff goes here -->
<?php $insert = "INSERT INTO Foods(Name, Type, NumCals, Healthy, Notes) VALUES ('$_POST[foodname]', '$_POST[foodtype]', '$_POST[foodcals]', '$_POST[foodhealth]', '$_POST[foodnotes]'";
$con = mysqli_connect("localhost","root");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db("mydb");
$result = mysqli_query($con, $insert);
if ($result) {
echo "Food added successfully.";
/*while ($row = mysqli_fetch_array($result)) {
echo $row['Name'] . ", " . $row['Type'] . ", " . $row['NumCals'] . ", " . $row['Healthy'] . ", " . $row['Notes'];
echo "<br>";
} */
} else {
echo "Error adding person";
mysqli_error($con);
}
} ?>
</body>
</html>
Schema:
Foods(PID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(PID),Name VARCHAR(20),Type VARCHAR(9),NumCals INT,Healthy BOOL,Notes TEXT)
This attribute in the submit button:
onclick="validateForm();return false;"
prevents the form from submitting. return false means that the browser should not perform the default action from clicking the button.
Assuming the validateForm() function returns a boolean indicating whether validation was successful, change that to:
onclick="return validateForm();"
Change:
} else {
echo "Error adding person";
mysqli_error($con);
to:
} else {
echo "Error adding person: " . mysqli_error($con);
So that the error message will be displayed.
And you're missing the ) at the end of your INSERT statement.