Check if <input> is empty or only whitespace - mysql

Some website's search boxes aren't very good: when you put a space in the search bar and submit, it returns every search item they have. (Example: http://watchfreemovies.unblocked.co/)
Mine does the same. What can I do to make it verify that there is actual text in the search box before submitting?
Search box and button:
<div class="Nava">
<input type="button" name="button" id="hello" value="M" />
</div>
<form action='/search.php' method='GET'>
<input id='searchbar' type='text' name='search' placeholder="search for movies & shows" maxlength="50" />
<input id='submit' type='submit' name='submit' value='Search' />
</form>
<div class="Navbuttons">
<input type="button" name="button" id="button" value="shows" />
<input type="button" name="button" id="button" value="movies" />
</div>
Results page:
$x = 0;
$construct = '';
$search = $_GET['search'];
$search = preg_replace("#[^0-9a-z ]#i", "", $search);
if (strlen($search) <= 0)
echo "Search term too short";
else {
echo "You searched for '<b>$search</b>' ";
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$search_exploded = explode(" ", $search);
foreach ($search_exploded as $search_each) {
$x++;
if ($x == 1)
$construct .= "keywords LIKE '%$search_each%'";
else
$construct .= "AND keywords LIKE '%$search_each%'";
}
$construct = "SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum == 0)
echo "<p>Sorry, there are no matching result for '<b>$search</b>'.</p>
<li> Try different words with similar
meaning</li>
<li> make sure you're spelling is correct</li>";
else {
echo "$foundnum results found !";
while ($runrows = mysql_fetch_assoc($run)) {
$title = $runrows['title'];
$desc = $runrows['description'];
$url = $runrows['url'];
echo "
<hr><a href='$url'><h2><b>$title</b></h2></a><br>
$desc<br>
<a href='$url'></a><p>
";
}
}
}

Check server-side:
if (!trim($_GET['search'])) {
echo 'Enter a query.';
}
Check client-side:
<form action='/search.php' method='GET'>
<input id='searchbar' type='text' name='search' placeholder="search for movies & shows" maxlength="50" required />
<input id='submit' type='submit' name='submit' value='Search' disabled />
</form>
<script>
document.getElementById('searchbar').onkeypress = function() {
document.getElementById('submit').disabled = !this.value.trim();
}
</script>
Fiddle

Related

how to make wordpress plugin form text field take numbers

I have a form in a plugin I am creatingin wordpress. The form is a simple test form and it has a hidden field and two text fields. If I enter a number into the text fields, it doesn't process it when I hit submit, it takes to me a page that says
It looks like nothing was found at this location. Maybe try a search?
here is the entire plugin showing the form and the action that processes the form.
<?php
/*
plugin name: deano plugin
description: deano test database to insert data into books table
author: Dean-O
*/
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once($path.'/wp-load.php');
function deanoinsertdata() {
/**
* Dean-O database insert book function
*/
global $wpdb;
if(isset($_POST['submitbtn'])){
error_log('I am here');
$data=array(
'wp_id'=>$_POST['wp_id'],
'title'=>$_POST['title'],
'author'=>$_POST['author'],
);
$table_name = 'books';
$foundOne = 1;
error_log('table_name = '.$table_name);
error_log('foundOne = '.$foundOne);
/*$wp_idin = $_POST['wp_id'];
$titlein = $_POST['title'];
$authorin = $_POST['author'];
*/
$wp_idin = $data['wp_id'];
$titlein = $data['title'];
$authorin = $data['author'];
error_log('wp_idin = '.$wp_idin);
error_log('titlein = '.$titlein);
error_log('author = '.$authorin);
/*
see if the record is already in the table
*/
$sql = "select * from books";
print $sql;
$results = $wpdb->get_results($sql);
foreach($results as $result) {
if($result->wp_id==$wp_idin && $result->title==$titlein && $result->author==$authorin)
{
$foundOne = 0;
error_log('foundOne = 0');
}
}
//error_log('logged message');
if($foundOne==1) {
error_log('foundOne = 1 before insert');
$resultinsert = $wpdb->insert($table_name,$data);//, $format=NULL);
error_log('insert executed');
error_log('resultinsert = '.$resultinsert);
//wp_redirect( "http://localhost/tadpolewp/deano-plugin--duplicate-records/" );
//exit();
if($resultinsert==1) {
//header('Location: http://localhost/tadpolewp/deano-plugin-successful/');
error_log( 'successful' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-successful/" );
exit();
http://localhost/tadpolewp/deano-plugin-successful/
//error_log('Book saved 1');
//echo "Book Saved 1";
} else {
//header('Location: http://localhost/tadpolewp/deano-plugin-failed/');
error_log( 'failed to save' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-failed/" );
exit();
//error_log('unable to save');
//echo "Unable to Save";
}
} else {
//error_log('Duplicate record found');
//echo "Duplicate recortd found";
//header('Location: http://localhost/tadpolewp/deano-plugin-duplicate-records/');
error_log( 'duplicate record' );
wp_redirect( "http://localhost/tadpolewp/deano-plugin-duplicate-records/" );
exit();
}
}
?>
<form role="form" method="post">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>
<?php
}
add_shortcode('deanoputdatain','deanoinsertdata');
?>
The only way I can get the Field 1 or Field 2 to take numbers is to change them to type="number"
Is there a varchar type that I can use?
My database has the field set as a varchar.
Thanks in advance
Dean-O
You should be set action for your form.
For example: 'test.php' or '/'.
It worked well for me. I rewrite your code here:
<form role="form" method="post" action="{your menu slug}">
<div class="form-group">
<?php
// get current user ID, with default value, if empty
$current_user_id = get_current_user_id();
?>
<input type="hidden" name="wp_id" value="<?php echo esc_attr( $current_user_id ); ?>" />
</div>
<div class="form-group">
<label>Field 1</label><br>
<input id="title" name="title" type="text" placeholder="<?php echo esc_attr( $current_user_id ); ?>" required="">
</div>
<div class="form-group">
<label>Field 2</label><br>
<input id="author" name="author" type="text" placeholder="Primary Author" required="">
</div>
<div class="row justify-content-center">
<div class="col-xs-4 col-sm-4 col-md-4">
<br><input type="submit" value="Submit1" class="btn btn-info btn-block" name="submitbtn">
</div>
</div>
</form>

How to connect my Login/Register for with MySQL database?

I started coding my website that we are gonna use to run business with my friend but i dont know how to connect my Login/Register page to mySQL database(running on xampp control panel with Apache server and MySQL server).
Any solution would be helpful. Thank you.
Login:
<link rel="stylesheet" type="text/css" href="loginstyle.css">
<form action="action_page.php">
<div class="container">
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="remember"> Remember me
</label>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Register:
<link rel="stylesheet" type="text/css" href="registerstyle.css">
<form action="action_page.php">
<div class="container">
<h1>Register</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<hr>
<p>By creating an account you agree to our Terms & Privacy.</p>
<button type="submit" class="registerbtn">Register</button>
</div>
<div class="container signin">
<p>Already have an account? Sign in.</p>
</div>
</form>
You will need to add PHP
Connect.php
<?php
/* Database connection settings */
$host = '';
$user = '';
$pass = '';
$db = '';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
?>
Add This to a different page with the extension to .php and Change action File to Login.php
Login.Php
session_start();
include("db.php");
if (isset($_POST['uname']) && isset ($_POST['pse'])) {
$username = $mysqli->escape_string($_POST['pse']);
$result = $mysqli->query("SELECT * FROM TABLE WHERE username='$username'");
if ( $result->num_rows == 0 ){
$_SESSION['message'] = "User with that email doesn't exist!";
echo '<script language="javascript">';
echo 'alert("'.$_SESSION['message'].'")';
echo '</script>';
}
else {
$user = $result->fetch_assoc();
if ( password_verify($_POST['Password'], $user['password']) ) {
$_SESSION['email'] = $user['email'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: System/index.php");
}
else {
$_SESSION['message'] = "You have entered wrong password!";
echo '<script language="javascript">';
echo 'alert("'.$_SESSION['message'].'")';
echo '</script>';
}
}
}
?>
Add This to a different page with the extension to .php and Change action File to Register.php
Register.php
<?php
session_start();
include("db.php");
if (isset($_POST['email']) && isset ($_POST['psw']) && isset ($_POST['psw-repeat'])){
$email = $mysqli->escape_string($_POST['email']);
$password = $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$password-repeat= $mysqli->escape_string(password_hash($_POST['password'], PASSWORD_BCRYPT));
$result = $mysqli->query("SELECT * FROM TABLE WHERE email='$email'") or die($mysqli->error());
if ( $result->num_rows > 0 ) {
$_SESSION['message'] = 'User with this email already exists!';
header("location: error.php");
}
if( $password !== $password-repeat){
$_SESSION['message'] = 'Password dont match';
header("location: error.php");
}
else {
$sql = "INSERT INTO TABLE( email, password)"
. "VALUES ('$first_name','$last_name','$email','$password', '$hash')";
header("location: index.php");
}
?>

trouble appending/combining two variables

Here's my code, It's a forum, there are posts with dislike buttons,like buttons, and a text box for commenting with each individual post, check the screenshot below. I'm trying to put the $comments variable, which are the comments itself, at the end of $posts so it displays below the posts properly like the like buttons and comment box are displayed.
I'm trying to just get the comments displayed underneath the comment box. If I call displayComments(the function in $comments definition) in the for each loop then the comments get displayed separately from the posts I've tried combining the $comments at the end of $posts with this operator +, and I've tried making a new variable equal to the both of them. Here's the code(not the full file).
<?php
include("connect.php");
include("check.php");
include("Trying.php");
include("Comment.php");
if(isset($_POST['username'])){
if (isset($_POST['post'])) {
if ($_FILES['postimg']['size'] == 0)
{
$postbody = $_POST['postbody'];
$loggedInUserId = check::isLoggedIn();
if (strlen($postbody) > 160 || strlen($postbody) < 1)
{
die('Incorrect length!');
}
connect::query('INSERT INTO dry_posts VALUES (null, :postbody, NOW(),\'\',0,0)', array(':postbody'=>$postbody));
}
}
if (isset($_POST['comment'])) {
$postid = $_GET['postid'];
$commentbody = $_POST['commentbody'];
if (strlen($commentbody) > 160 || strlen($commentbody) < 1) {
die('Incorrect length!');
}
connect::query('INSERT INTO comments VALUES (null,:comment, NOW(), :postid)',array(':comment'=>$commentbody,':postid'=>$postid));
//}
}
$dbposts = connect::query('SELECT * FROM dry_posts ORDER BY id DESC');
$posts = "";
$comments = Comment::displayComments($p['id']);
foreach($dbposts as $p){
if (!connect::query('SELECT post_id FROM dry_likes WHERE post_id=:postid', array(':postid'=>$p['id']))) {
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
;
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
else{
$posts .="<img src='".$p['postimg']."'>".htmlspecialchars($p['body'])."
<form action='try.php?postid=".$p['id']."' method='post'>
<input type='submit' name='like' value='Like'>
<span>".$p['likes']." likes</span>
<input type='submit' name='dislike' value='Dislike'>
<span>".$p['dislikes']." dislikes</span>
</form>
<hr /></br />
<form action='try.php?postid=".$p['id']."' method='post'>
<textarea name='commentbody' rows='3' cols='50'></textarea>
<input type='submit' name='comment' value='Comment'>
</form>
<hr /></br />
";
//Comment::displayComments($p['id']);
}
}
?>
<form action='try.php' class = "forum" method="post" enctype="multipart/form-data">
<textarea name="postbody" rows="4" cols="60" class = "text"></textarea>
<br />Upload an image:
<input type="file" name="postimg">
<input type="submit" name="post" value="Post">
</form>
<div class="posts">
<?php echo $posts;
?>
</div>
Here's the function I'm calling in the $comments variable
public static function displayComments($postid)
{
$comments = connect::query('SELECT * FROM comments WHERE post_id=:postid',array(':postid'=>$postid));
foreach($comments as $comment)
{
echo $comment['comment']."<hr />";
}
}
I know this won't help a lot of people but I'm just not sure what to do, How do you suggest I get everything to display inline, should rearrange my code?

MySQL Result in $row will not echo in if conditional

I am trying to get the row queried in preceding code to echo inside of this if conditional if the user clicks the modify video link. However, when I echo the $video variable directly above the if ($videoEdit) { conditional, it displays on page, but if I try to echo it inside the if ($videoEdit) { conditional, it will not output for some reason. I'm confused. Here is my code (query not included, but echo $video does output proper results before conditional)
Addition:::
require ('../mysql_connect.php'); // Connect to DB
// Handle Video Edit
if ($_GET['video'] == "EDIT") {
$videoEdit = TRUE;
}
$query = "SELECT inventory.inv_key, inventory.mdl_key, inventory.serial, inventory.date_aquired, inventory.location, inventory.price, model.mdl_key, model.man_key, model.cls_key, model.sub_cls_key, model.model, model.video, model.picture, model.pdf, subclass.sub_cls_key, subclass.subclass, class.cls_key, class.class, manufacturer.man_key, manufacturer.manufacturer FROM inventory, manufacturer, model, class, subclass WHERE inventory.mdl_key='$_GET[mdl_key]' AND model.mdl_key='$_GET[mdl_key]' AND class.cls_key='$_GET[cls_key]' AND subclass.sub_cls_key='$_GET[sub_cls_key]' AND manufacturer.man_key='$_GET[man_key]' AND manufacturer=manufacturer.manufacturer AND class=class.class AND subclass=subclass.subclass";
$result = #mysql_query ($query); // Run the query
while ($row = mysql_fetch_array
($result, MYSQL_ASSOC)) {
$model = $row['model'];
$mdl_key = $row['mdl_key'];
$video = $row['video'];
$picture = $row['picture'];
$pdf = $row['pdf'];
$description = $row['description'];
$manufacturer = $row['manufacturer'];
$man_key = $row['man_key'];
}
Addition Above::::
if ($_GET['video'] == 'EDIT') {
$videoEdit = TRUE;
}
while ($row = mysql_fetch_array($result)) {
$video = $row['video'];
}
if ($videoEdit) { // <-- boolean comparison
echo '<form action="edit_media.php" method="post">
<p>Video Link: <input type="text" name="serial" size="25" maxlength="100" value=';
if (isset($video))
echo $video;
}
echo ' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />
</form>';
}
Addition:: this is, in my code, directly below the above code
if ($video != "") {
echo '<iframe width="420" height="315" src=' . $video . ' frameborder="0" allowfullscreen></iframe> | <a href=edit_media.php?video=EDIT&mdl_key=' . $mdl_key . '&man_key=' . $man_key . '>Modify Video Link</a>';
} else {
echo "Video Not Present | <a href=edit_media.php?video=EDIT>Add a Video</a>";
}
You are missing an echo before the remainder of your html string ' />< /p>...'
if (isset($video))
echo $video;
echo ' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" /></form>';
Most likely, $video is not set.
You should try to echo $video; after the while loop. Also, you should not be using a loop unless if you're only fetching a single result.
$row = mysql_fetch_array($result);
$video = $row['video'];
echo $video;
Update
Here's how I would approach your problem (obviously replacing mysql_ functions):
if ($_GET['video'] == 'EDIT') {
$result = mysql_query("SELECT ... ");
$row = mysql_fetch_array($result);
$video = $row['video'];
echo '<form action="edit_media.php" method="post">
<p>Video Link: <input type="text" name="serial" size="25" maxlength="100" value='";
if (isset($video)) {
echo $video;
}
echo '" /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />
</form>';
}
}
Also noticed that you were missing the open curly bracket ({), and double quotes around the value of $video in the HTML.
Not sure if this is the answer, but looks like you need another "echo" before continuing the loop, after trying to echo out the $video content. Before this:
' /></p><p><input type="submit" name="submit" value="Submit Video" /></p> <input type="hidden" name="submitted" value="TRUE" />

mySQL query returns only one result

I am trying to get each row in a table to appear as part of a survey. The following code is returning only the first row in the table (so users can see only one question). I've been over and over this and can't see what I'm doing wrong. Would much appreciate any input.
Thank you!
function getQuestions ($dbc) <!--$dbc=database connection--> {
$query = "SELECT * FROM survey_questions" <!--survey_questions=table--> ;
$result = #mysqli_query ($dbc, $query);
while ($row = mysqli_fetch_array ($result, MYSQLI_ASSOC) ) {
$body = $row ['question_body'] <!--question_body=row in table--> ;
echo '
<div class="entry"> <!--user entry form-->
<h3 class="qTitle">'.$body.'</h3>
<form action="index.php" method="post">
<input type="text" name="answer" size="85" />
<input type="submit" value="Submit" name="submit" />
<input type="hidden" name="questionid" value="questionid" />
<input type="hidden" name="submitted" value="1" />
</form>
</div>
';
}
}
First of all you don't need to echo so much using php...
You have to use // or /* */ to comment in PHP and not <!----> cuz that's for HTML
Secondly coming to your code..
Why you are using?
function getQuestions($dbc) //I dont know what this is doing here, why you are wrapping your code in a function???
you can simply write like this (use echo to print out your question):
<?php
$result = mysqli_query($dbc, "SELECT * FROM survey_questions");
while ($row = mysqli_fetch_array ($result) ) {
?>
<div class="entry"> <!--user entry form-->
<h3 class="qTitle"><?php echo $row['whatever']; ?></h3>
<form action="index.php" method="post">
<input type="text" name="answer" size="85" />
<input type="submit" value="Submit" name="submit" />
<input type="hidden" name="questionid" value="questionid" />
<input type="hidden" name="submitted" value="1" />
</form>
</div>
<?php
}
?>
The results are now two entry forms (an improvement) but still not displaying the text of the two rows from the database. Instead of the row text, I get the > character where the text should be. Here is the updated code, adapting the suggestion of #Mr. Alien:
function getQuestions($dbc) {
$result = mysqli_query($dbc, "SELECT * FROM survey_questions");
while ($row = mysqli_fetch_array ($result) ) {
echo '
<div class="entry">
<h3 class="qTitle">'. $row['survey_questions'].'></h3>
<form action="index.php" method="post">
<input type="text" name="answer" size="85" >
<input type="submit" value="Submit" name="submit" >
<input type="hidden" name="questionid" value="questionid" >
<input type="hidden" name="submitted" value="1" >
</form>
</div>
';
}
}