I have this function on my php:
function getLastMatchs($nb) {
try
{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
die('connexion failed: '.$e->getMessage());
}
$i=0;
$get5tmatchs = $db->query('SELECT wid, lid, date, cwid, clid FROM `match`');
while ($nb<$i)
{
$data5matchs = $get5tmatchs->fetch();
echo '<tr>
<td>'.$data5matchs['wid'].'</td>';
echo '<td>'.$data5matchs['lid'].'</td>';
echo '<td>'.$data5matchs['cwid'].'</td>';
echo '<td>'.$data5matchs['clid'].'</td>';
echo '<td>'.$data5matchs['date'].'</td>
<br>
</tr>';
$i++;
}
}
And my form is:
echo '<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>';
echo getLastMatchs('nbmatchs');
How can i do for show nbmatch time the guys want my table ?
When i do now, nothing happen.
Thanks for your help
PS: For exemple i tape 5, i can see 5 time the tabe i have put in my function.
What you indended to accomplish (as far I understood) to allow a visitor enter a numer and then submit it after what some "matches" data it shown. The number visitor entered acts as a limiter.
1. Where do you get your POST variables? You have placed a function below the form with an input value of string 'nbmatchs'. I guess you wanted to submit the form and get the 'nbmatches' value and then apply it to the SQL query for filtering. The way you have done it doesn't work. You have action attribute on your form element set to index.php. That's where we are going to submit the form data. So we need to have a way to get the submitted POST variables. We do it like this:
$nbmatchs = $_POST['nbmatchs'];
Never trust data client has given you. As we know that it must a number let's do a check on it:
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
Above we checked if the data client has given really is a number. If it is we'll assign this nubmer to variable $nbmatches. If the data client has given is not a number (eg. some string) we assign number 1 to the variable. At this point we may end the script execution a let the visitor know he must enter a number but we just assign 1 to the variable if anything seems suspicious. After that we can submit this variable to the function getLastMatchs which takes the variable and assigns it to the SQL query as a results limiter. Assuming that all the code will be in one file 'index.php' you should have the following code:
<?php
function getLastMatchs($nbmatches) {
try{
$db = new PDO(DBHOST, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die('connexion failed: '.$e->getMessage());
}
try {
$select = $db->prepare('SELECT wid, lid, date, cwid, clid FROM `match` LIMIT '.$nbmatches.';');
$select->execute();
$results = $select->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $ex) {
echo "<span style='color:red'>".$ex->getMessage()."</span></p>";
}
echo '<table>';
foreach($results as $result){
$output = '<tr>';
$output .= '<td>'.$result['wid'].'</td>';
$output .= '<td>'.$result['lid'].'</td>';
$output .= '<td>'.$result['cwid'].'</td>';
$output .= '<td>'.$result['clid'].'</td>';
$output .= '<td>'.$result['date'].'</td>';
$output = '</tr>';
echo $output;
}
echo '</table>';
}
if(isset($_POST['nbmatchs'])){
$nbmatches = is_numeric(trim($_POST['nbmatchs'])) ? $_POST['nbmatchs'] : 1;
getLastMatchs($nbmatches);
}
?>
<form action="index.php" method="post">
<h3>My question......</h3>
<p>
<input type="text" name="nbmatchs" />
<input type="submit" value="ok" />
</p>
</form>
Let me know if this works the way you wanted.
Related
I am using a form. (I wanted the message text as a text area but changed back to normal text to see if this was the problem)
This is the form I am using
<form name="addmessage" method="POST" action="addmessage.php" >
<input type="text" name="message_title" id="message_title">Message Title</input>
<input type="text" name="message_text" id="message_text">Message</input>
<input type="submit" name="submit" value = Add>
</form>
Below is the PHP code. I understand i need to protect against sql injection however, i can do this later.
<?php
include_once("config.php");
if(isset($_POST["message_title"]) && strlen($_POST["message_title"])>0)
{
$message_title=$_POST['message_title'];
$message_text=$_POST['message_text'];
session_start();
$barber_id = $_SESSION['barber_id'];
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
}
else
{
//Output error
header('HTTP/1.1 500 Error You have left it blank');
exit();
}
header("location:messages.php");
?>
If manually enter data using phpMyAdmin, I can get it to display using the code below.
include_once("config.php");
session_start();
$barber_id = $_SESSION['barber_id'];
$results = $mysqli->query("SELECT * FROM messages WHERE barber_id ='$barber_id' ");
//get all records from table
while($row = $results->fetch_assoc())
{
$prices_id = $row['prices_id'];
echo '<div data-role="collapsible">';
echo '<h1>';
echo ' Message Title: ';
echo $row['message_title'];
echo '</a>';
echo '</h1>';
echo '<p>';
echo $row['message_text'];
echo ' Delete</div>';
}
$mysqli->close();
?>
At $insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."',".$message_text.")");
you should write
$insert_row = $mysqli->query("INSERT INTO messages(barber_id,message_title,message_text) VALUES('".$barber_id."','".$message_title."','".$message_text."')");
Everytime you pass a String or other non int values you must pass them like that: 'xx', otherwise mysql will see it as query param and it crashes.
I have a PHP website to display products. I need to introduce a 'Search' feature whereby a keyword or phrase can be found among number of products.
I went through number of existing scripts and wrote/modified one for me which though able to connect to database, doesn't return any value. The debug mode throws a warning " mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given ". Seems I am not collecting the query value correctly. The PHP Manuals says that mysqli_query() returns FALSE on failure and for successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object and for other successful queries mysqli_query() will return TRUE ".
Any suggestions?
<form name="search" method="post" action="search.php">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
<?php
$searchterm=trim($_POST['searchterm']);
$searching = $_POST['searching'];
$search = $_POST['search'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo 'Results';
//If they forget to enter a search term display an error
if (!$searchterm)
{
echo 'You forgot to enter a search term';
exit;
}
//Filter the user input
if (!get_magic_quotes_gpc())
$searchterm = addslashes($searchterm);
// Now connect to Database
# $db = mysqli_connect('localhost','username','password','database' );
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to the database. Please try again later.';
exit;
}
else {
echo "Database connection successful."; //Check to see whether we have connected to database at all!
}
//Query the database
$query = "SELECT * FROM wp_posts WHERE post_title LIKE '%$searchterm%' OR post_excerpt LIKE '%$searchterm%' OR post_content LIKE '%$searchterm%'";
$result = mysqli_query($db, $query);
if (!$result)
echo "No result found";
$num_results = mysqli_num_rows($result);
echo "<p>Number of match found: ".$num_results."</p>";
foreach ($result as $searchResult) {
print_r($searchResult);
}
echo "You searched for $searchterm";
$result->free();
$db->close();
}
To do your literal search as you have it, you would need to change the code '%{searchterm}%' to '%$searchterm%', since the brackets aren't needed and you were searching for the phrase "{searchterm}." Outside of that you might want to take a look at FULLTEXT search capabilities since you're doing a literal search in your current method.
To make the output look like Google's output you would simply code a wrapper for each search result and style them with CSS and HTML.
I think it should be something like '%$searchterm%', not '%{searchterm}%' in your query. You are not searching for your variable $searchterm in your example.
Google's display uses LIMIT in the query so it only displays a certain amount of results at a time (known as pagination).
This is tested and works. You will need to change 1) db connection info in the search engine class. 2) If you want it to be on separate pages, you will have to split it up. If not, copy this whole code to one page and it will work on that one page.
<?php
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
class SearchEngine
{
protected $searchterm;
public function execute($searchword)
{
$this->searchterm = htmlentities(trim($searchword), ENT_QUOTES);
}
public function display()
{ ?>
<h1>Results</h1>
<?php
//If they forget to enter a search term display an error
if(empty($this->searchterm)) { ?>
<h3>Search Empty</h3>
<p>You must fill out search field.</p>
<?php }
else {
$con = new DBEngine('localhost','database','username','password');
$results = $con->Fetch( "SELECT * FROM wp_posts WHERE post_title LIKE '%".$this->searchterm."%' OR post_excerpt LIKE '%".$this->searchterm."%' OR post_content LIKE '%".$this->searchterm."%'");
if($results !== 0 && !empty($results)) { ?>
<p>Number of match found: <?php echo count($results); ?> on search:<br />
<?php echo strip_tags(html_entity_decode($this->searchterm)); ?></p>
<?php
foreach($results as $rows) {
echo '<pre>';
print_r($rows);
echo '</pre>';
}
}
else { ?>
<h3>No results found.</h3>
<?php
}
}
}
}
if(isset($_POST['submit'])) {
$searcher = new SearchEngine();
$searcher->execute($_POST['searchterm']);
$searcher->display();
} ?>
<form name="search" method="post" action="">
<input type="text" name="searchterm" />
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="Search" />
</form>
i am trying to create a form and in that form have a selection list in which the options are automatically populated with data from a database (namely customer's last names), after which when the last name is chosen from the list and the submit button is hit the "customer ID" that is related to that last name in the database will be submitted to another PHP file (task8.php) to be sent through further queries. I hope i have explained that all in an understandable manner. I have had a go at some code but i am really unsure on how to do this or if what i have written is on the right path.
Here is what i have written so far:
<body>
<?php
$conn = mysql_connect("localhost", "twa312", "dam6av9a");
mysql_select_db("warehouse312", $conn)
or die ('Database not found ' . mysql_error() );
$sql = "select customerID, lastName from customer";
$rs = mysql_query($sql, $conn)
or die ('Problem with query' . mysql_error());
$options= '<option value="0">Choose</option>';
while ($row=mysql_fetch_array($rs)) {
$id=$row["customerID"];
$name=$row["lastName"];
$options="<OPTION VALUE='" . $id . "'>" . $name ."</option>";
}
?>
<form method="GET" action="task8.php" id="custinfo" >
Choose name:<select name="lname" id="lname"><?php echo $options; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
What i am trying to do with the code is access the table "customer" and fields "customerID" and "lastName". Using the customer's last name as the option and the customer's ID as the options value in the selection list. Currently the code displays only a single name as an option in the selection list when it should display all the names in the database. Any help on this would be really great as i am fairly unsure.
There is an error in the code that I can see would cause PHP to generate notice error.
In the while loop you're using .= on the $options variable that isn't yet defined so PHP will barf on that.
Aside from that, it doesn't make sense to me that you're waiting for $_GET['submit'] to be set before iterating over the result set from mysql. As far as I can tell, the first time you'd hit this page there would be a single option in the select ("Choose"), and since the form submits to a different page I don't think you'd ever see a list of customer last names.
Finally, it's not really recommended to name your submit buttons 'submit', since when the page is parsed by the browser all the form elements of a specific form are created as attributes of that form, JS form objects have a 'submit' method so when you name an input 'submit' you clobber that value in the form object which makes it really hard to submit that form with JS.
First off move away from the mysql_functions.
Secondly create a model with all querys related to your customers that will handle fetching/puttin/updating the data related to your customer db.
<?php
Class CustomerModel{
private $db;
function __construct($host,$dbname,$user,$pass){
$this->dbhost = $host;
$this->dbname = $dbname;
$this->dbuser = $user;
$this->dbpass = $pass;
}
private function connect(){
if (!$this->db instanceof PDO){
$this->db = new PDO('mysql:dbname='.$this->dbname.';host='.$this->dbhost, $this->dbuser, $this->dbpass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
}
}
public function select_all_customer($cols="*"){
$this->connect();
$sql = "SELECT $cols FROM customer";
$statement = $this->db->prepare($sql);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
public function select_customer($cols="*",$where=null, $id=null){
$this->connect();
$sql = "SELECT $cols FROM customer WHERE $where = :id";
$statement = $this->db->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_STR);
$statement->execute();
return $statement->fetchAll(PDO::FETCH_ASSOC);
}
}
?>
Now you can access the model like:
<form method="POST" action="task8.php" id="custinfo" >
Choose name:
<select name="customerID" id="customerID">
<option value="0">Choose</option>
<?php foreach($customer->select_all_customer("customerID, lastName") as $row): ?>
<option value="<?php echo $row['customerID']?>"><?php echo $row['lastName']?></option>
<?php endforeach; ?>
</select>
<p><input type="submit" name="submit" value="Save Data"/> <input type="reset" value="Clear Form" />
</form>
<?php
//Get customer from form values
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST['customerID'])){
$result = $customer->select_customer("*", "customerID", $_POST['customerID']);
//Do something with result
echo '<pre>'.print_r($result, true).'</pre>';
}
?>
Hope it helps
I need some help I am trying to create a PHP form using sqlite3 database. I am looking up values from from an existing sqlite3 database in the table2 where the column id = 340 and display those values as a dropdown selection. Then once the value is selected by the user then the form is submitted by the users which updates the new values to the table1 with the values from the php form. I get it to display the names in the dropdown but when I click on the update button to submit the data it updates what the value is in the array.
For example lets say I have 3 fruits in the table and I select pear it updates the table with a "1" instead of the word "pear"
apple
pear
peach
PHP entry page Code:
<html>
<head>
<title></title>
</head>
<div class = "controlbox">
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
<h1> </h1>
<br>
<br>
Slot1 : <select name="slot1">
<option>--Available Options--</option>
<?php
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
$stmt2 = $db->query ("SELECT * FROM table2 where ID = '340' ");
$rowarray = $stmt2->fetchall(PDO::FETCH_ASSOC);
$slot1 = 0;
foreach($rowarray as $row)
{
echo "<option value = $slot1 >$row[FirstName] $row[LastName]</option>";
$slot1++;
}
?>
</select><br>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e)
{
echo $e->getMessage();
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE table1 SET Slot1place = :slot1 WHERE ID = '340'");
$stmt->bindParam(':slot1', $slot1,PDO::PARAM_STR);
$stmt->execute();
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "submitted successfully";
}
?>
You dont use sqlite_escape_string if youre using a prepared statement like that. The values are going to be quoted witn they are bound to the statement.
I think you should check your html syntax (Is it missing tags, and the ).
Check it out at: http://www.w3schools.com/html5/tag_option.asp
echo "<option name = $name >$row[FirstName] $row[LastName]</option>";
Everything else is the right syntax
So I'm working on app that involves leveraging user profile data from FB. But not all users maintain the same data, so I'm using functions to determine which data is missing and then request the appropriate data from the user. These requests come from a database. A basic example of the function looks like this:
function getEmploymentInfo () {
if (isset($this->employer) and (!isset($this->jobtitle))) {
$id = 1;
} elseif (!isset($this->employer)) {
$id = 2;
}
echo $this->get_profile($id);
}
And the get profile function looks like this:
function get_profile($id) {
$dsn = "mysql:host=localhost;dbname=software";
$username = "root"; // database username
$password = "*******"; // database password
try {
$enter = new PDO($dsn, $username, $password);
$sql = "SELECT response FROM getprofile WHERE response_id = ? ";
$new_item = $enter->prepare($sql);
$new_item->setFetchmode(PDO::FETCH_ASSOC);
$new_item->execute(array($id));
foreach($new_item as $nw) {
return $nw['response'];
}
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
return "";
}
And $id=1 coming from the database looks like this:
<script type="text/javascript">
function getJobTitle(){
document.getElementById("JobTitle").hidden = true;
document.getElementById("two").hidden = false;
}
function getStartDate(){
document.getElementById("StartDate").hidden = true;
document.getElementById("three").hidden = false;
}
function getEndDate(){
document.getElementById("EndDate").hidden = true;
document.getElementById("four").hidden = false;
}
<?php
echo "$objUser->employer";
?>
<form action="newprofile.php" method="post">
<p><a id="JobTitle" href="#" onclick="getJobTitle()">Add Job Title</a><input type="text" name="jobtitle" id="two" hidden="true" value="Add Job Title"></input></p>
<p><a id="StartDate" href="#" onclick="getStartDate()">Add Start Date</a><input type="text" name="startdate" id="three" hidden="true" value="Add Start Date"></input></p>
<p><a id="EndDate" href="#" onclick="getEndDate()">Add End Date</a><input type="text" name="enddate" id="four" hidden="true" value="Add End Date"></input></p>
<input type="submit" value="submit"></form>
But when this code returns from the database to the page echo "$objUser->employer"; doesn't populate. Meanwhile if I write that code directly on the page it works. What gives?
Databases just store text, not actual instantiated objects. The returned value has no way of knowing what $objUser was when you stored all that text.
There's a lot of things wrong with the way you're trying to go about doing this, you shouldn't be storing all that code in the database for every row. But the most simple way to answer this and point you in the right direction, is that you need to serialize objects in order to store them in the database, and unserialize them after pulling the record out of the database, in order to use them again.