I am trying to create a function that will check against the data from the database. If the results are empty, continue with the code. If else, abort.
Here is an example of my code.
function check_if_blocked(){
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(empty($results)){
$var = false;
} else {
$var = true;
}
return $var;
}
Function check_if_blocked is going to be used multiple through out the plugin.
Here is an example of how I plan on using check_if_blocked()..
function msg_form(){
if(check_if_blocked(){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send">';
}
}
Regardless on how I switch around the true, false, and even if(!check_if_blocked...
You are trying to return the wrong value, get_results will return true if the query was successful, not if it found matches, so, it might return true even if there are no matching records found, try this instead:
function check_if_blocked()
{
global $wpdb;
$user = '1';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE user = $user");
if(!$results) {return false;} // query failed, no way to know if there are matching records.
$numrows = count($results); // query worked, now, check if there are matching records.
if (is_int($numrows) && $numrows) {$var = true;} else {$var = false;}
return $var; // return the result.
}
Now, the function will return true only if there are one or more matching records.
Also, you have a syntax error here:
if(check_if_blocked(){
It should be:
if(check_if_blocked()){
After everyone's advice. I finally got it to work. Here is my code.
function check_if_blocked($blocked){
global $wpdb;
$user = '1';
$user2 = '2';
$results = $wpdb->get_results("SELECT * FROM mytable WHERE blocked = $user AND blocker = $user2");
if(empty($results)){
$blocked = 'not_blocked';
} else {
$blocked = 'is_blocked';
}
}
function msg_form(){
if(check_if_blocked($blocked) == 'not_blocked){
echo '<form action="" method="post">
<input type="text" name="msg">
<input type="submit" name="submit" value="send"></form>';
}
}
Related
I would like to ask, what will be the best way to code using SQL and PHP, on how to check if the input in a textfield matches with a value in an SQL column?
I only have three values in the table. my targets are:
retrieve (POST) the value of the input
check the whole column to see if any matches the "promo code" typed
the "tinyint" used value will turn to 1
echo or affect other database tables if conditions are met
pseudocode will be alright, I would just like the proper procedure.
UPDATE: I tried the solution from #Bitwise Creative, im not getting an echo to appear, which part did i do wrong? also, i got my db where the table is located using a variable.
<form method="get">
<input type="text" name="lux_code" placeholder="ENTER PROMO CODE" style="text-align:center;">
<input type="submit" class="full_width btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</form>
<?php
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
if (isset($_POST['lux_code']) && $_POST['lux_code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM promocode_3 WHERE coupon_code = ? AND used = ?', array($_POST['lux_code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE promocode_3 SET used = ? WHERE coupon_code = ?', array(1, $_POST['lux_code']));
// Additional handling...
echo 'Code accepted!';
}
}
}
?>
Assuming coupon_code has a unique index... Something like:
<?php
if (isset($_POST['code']) && $_POST['code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM coupons WHERE coupon_code = ? AND used = ?', array($_POST['code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE coupons SET used = ? WHERE coupon_code = ?', array(1, $_POST['code']));
// Additional handling...
echo 'Code accepted!';
}
}
You can do like this-
$couponcode = $_POST['coupon'];
$sql = "update table_name set used = 1 where coupon_code = $couponcode && used = 0";
The best way is to retrieve all your unused coupon codes and then iterate over the collection and check if the posted value is a match.
I would write a function in my functions.php file as so:
function getCoupons() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM coupons WHERE `used` = 0");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
I would then call the function and store the results into an array in my test.php file like so:
$coupons = getCoupons();
I would also need the posted value, I'll retrieve it like so:
$couponCode = $_POST['coupon'];
I would then iterate over the result set to check for a match in the same file:
$match = false;
foreach($coupons as $coupon){
if($coupon['coupon_code'] == $couponCode){ //check to see if posted value matches
$match = true;
$stmt2 = $db->prepare("UPDATE coupons SET used =
'1' WHERE p3id = :id");
$stmt2->execute(array(
':id'=>$coupon['id']
));
break;
}
}
if($match){
echo 'Coupon code exists!';
} else {
echo 'No Coupon code exists!';
}
I have a list of buttons that each pass on a different value. The code should store this value as a variable or session, which then is passed on to a function that updates the table row of the value. I tried just storing this value as a variable and then passing it on, but that didn't work so I figured I'd make it into a session. And that didn't work either, no idea where to go from here.
Here's a button example:
<tr>
<td data-title="Name"><img src="banner.jpg" width="400"></td>
<td data-title="Link">
<form name="first" action="pending.php" method="POST"><input type="hidden" name="xz" value="one"><a class="mbutton" onclick="document.forms['first'].submit();">Gedaan</a></form>
</td>
<td data-title="Status"><p class="ptable"><?= $fgmembersite->One(); ?></p></td>
</tr>
Here's where the form leads to:
<?PHP
include("./include/membersite_config.php");
$_SESSION['postdata'] = $_POST;
$bname = $_SESSION['postdata'];
if($fgmembersite->Pending($bname))
{
$fgmembersite->RedirectToURL("index.php");
}
?>
So this should pass on $bname to the function Pending().
And here's pending:
function Pending($bname)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$result = mysql_query("Select * from $this->tablename where confirmcode='y'",$this->connection);
if(!$result || mysql_num_rows($result) <= 0)
{
$this->HandleError("Error");
return false;
}
$row = mysql_fetch_assoc($result);
$ux = $row['username'];
$ustat = $row['one'];
$bname = $_SESSION['postdata']['xz'];
$qry = "Update $this->tablename Set $bname='In behandeling' Where username='$ux'";
if(!mysql_query( $qry ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$qry");
return false;
}
return true;
}
So you are saying that the Pending function is returning TRUE, and redirecting you to membership.php ? or index.php ( or are these the same ) -
if that query fails and returns false - you would just end up on the page that you had posted to .
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 using Codeigniter and I have created a code that checks if there is the same entry already in the database. but i dont know how i will output the error message. the boolean is not working.
VIEW
<h8><b>Add New Service: For single upload. <?php echo $status; ?></b></h8><hr>
<form action="<?php echo base_url(); ?>some_controller/insertServ" method="post">
<center>Service Name: <input type="text" name="ci_name"/>
<input type="submit" class="classname" value="Save"/></center>
</form>
CONTROLLER
public function insertServ(){
/* logic behind adding a new service
*/
$ci_name = $this->input->post('ci_name');
$success = $this->some_model->addCI($ci_name);
if($success == TRUE)
$this->viewMap_add(TRUE);
else $this->viewMap_add(FALSE);
}
public function viewMap_add($success = NULL){
/* Shows the list of the services with a dialog box for
* adding a new service
*/
if($success == NULL)
$status = 'N/A';
else if($success == TRUE)
$status = 'Success';
else $status = 'FAILED';
$data['status'] = $status;
$data['current_user']=$this->session->userdata('email');
$data['mapList'] = $this->some_model->getMapped();
$this->load->view('templates/header.php',$data);
$this->load->view('some_page/servList_add.php',$data);
}
MODEL
public function addCI($ci_name){
/* Adds a new service
*/
$ci_name = $this->db->escape_str($ci_name);
$queryStr = "Select service from appwarehouse.service where service = '$ci_name'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
echo "result already exists";
}
else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$ci_name');";
$query = $this->db->query($queryStr);}
}
First off, your model method addCI isn't returning anything. Fix that.
Then, you can avoid all the mess by simply removing one layer of code and sending the status value directly:
public function insertServ:
if($success)
$this->viewMap_add('Success');
else
$this->viewMap_add('FAILED');
And then just remove all the if-elses in the viewMap_add method.
Also, since you didn't tell exactly what is the problem, try doing the var_dump on the status variable in insertServ or just:
var_dump($this->some_model->addCI($ci_name));
UPDATE
Here is how your model method should look like (nothing to echo there, but return a boolean):
public function addCI($ci_name){
/* Adds a new service
*/
$ci_name = $this->db->escape_str($ci_name);
$queryStr = "Select service from appwarehouse.service where service = '$ci_name'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return false; // <---- this one is important
}
else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$ci_name');";
$query = $this->db->query($queryStr);
return true; // <---- and this one
}
}
I was wandering how you would go about sending a form to different pages.
If there is an error in the form, stay on the page, showing an error and if there is no error go onto another page
here is my code
<form id = "form" action = "./?page=markandfeedback" method = "post">
<br>
Mark for:
<INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar" value="Enter Student Number" style="min-width:165px;">
<input type="button" value = 'Continue' onclick="validate()">
<?
$studID = $_POST['txtChar'];
$module2 = $_SESSION['module'];
$ex = $_POST['exer'];
$studerr = array();
$sql = 'SELECT * FROM `student`, `modules` WHERE `studentID` = '.$studID.' AND `moduleCode` = '.$_SESSION['module'];
$result = mysql_query ($sql);
echo $_SESSION['module'];
if(isset($studID)){
if($result == null){
$studerr[] = "No Student with that ";
print_r($studerr);
}
$_SESSION['student'] = $studID;
}
echo' <SCRIPT TYPE="text/javascript" LANGUAGE="javascript">
function validate() {
if('.$result.' == null)
{
return false
}
else
{
return true;
}
}
</script>';
?>
</form>
cheers
Very briefly (without knowing other details):
if (!empty($errorMessage)) {
echo $errorMessage;
} else {
header("Location: http://domain.com/success.php");
}
Have you searched something about that ???
YOu can use normal php validation for error checking and
if(there is no error )
{
header('location: redirect2page.php')
}
else
{
show errors
}
you have to do simple javascript validation in form submit if error occures it will return false so, thats remain on same page
like
function validate()
{
if(document.getElementById('elementid').value=='')
{
return false;
}
else
{
return true;
}
just call this function on submit button click