My search form does not seem to work - php

I want my search form to display users(username,firstname or lastname) from my database and display them as the user is typing like how facebook and twitter do but when i click search,nothing happens.Here are 2 parts of my header inc that deal with the search form,1st part:
<?php
include( "Connect.php" );
ob_start(); session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else {
$username = "";
}
$output = "";
//Collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = $mysqli->query("SELECT * FROM users WHERE first_name LIKE '%$searchq%' OR last_name LIKE '%$searchq%'") or die("could not search!");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while($row = mysqli_fetch_array($query)) {
$fname = $row['first_name'];
$lname = $row['last_name'];
$id = $row['id'];
$output .= '<div> '.$fname.' '.$lname. '</div>';
}
}
}
?>
2nd part:
<form id="searchForm">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" name="search" value="Go" id="search" />
</p>
</div>
</form>
<?php print ("$output"); ?>

invalid action name
action="header inc.php"
you cannot use space in .php files
Edit the filename as headerInc.php and pass it in the form as:
action="headerInc.php"

I have changed your html code , just use it and it will start working. In your html there is hierarchy of form tag , I have added method post to first form and I have replaced the name of the text field by submit button name. In each post your data value was "go".
I hope it will resolve your problem :
<form id="searchForm" method="post">
<fieldset>
<div class="input">
<p>
<form action="header inc.php" method="post">
<input type="text" class="Search" name="search" id="search" size="35" placeholder="Search username,fullname or topic"/>
<label for="Submit"></label>
<input type="submit" value="Go" id="search_button" />
</p>
</div>
</form>
<?php echo $output; ?>

Related

Call out value into input field in PHP

How to display SQL result into text input?
When I press the generate button it should appear in the input text.
<?php
$random_name = "";
$conn = mysqli_connect("localhost","root","","wordlist");
if(!$conn)
{
die("Connection Error!");
}
$query_random = "SELECT kata FROM list ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn,$query_random);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$random_name = $row["kata"];
}
}
mysqli_close($conn);
?>
</head>
<body>
<div class="container" >
<form action="#">
<h4>Word Generator : </h4>
<div class="form-group">
<input type="text" class="form-control">
</div><br>
<button id="generate-btn" type="submit" title="Generate Word">Generate</button>
</div>
</form>
You just need to add this in place of your input, your code is correct but you missed to print the value, that's all
<input type="text" class="form-control" value="<?php echo #$random_name ?>">

Display of database fetched data in HTML through PHP

I have an textarea to create an article, which then gets loaded into the db.
Also i have a function to fetch an article by chapter number to display it on the site.
The function works well, but the fetched data, or better said all echos from the PHP function get right into the body-tag which kills my layout.
I'd like to know, how can I display the data from the PHP output into a specific area in my HTML?
index.html:
<body>
<div class="main">
<h1>WebDev's Playground</h1>
<p>Momentaner Versuch: Formatierte Texte in Datenbanken speichern.</p>
<div class="playground">
<form action="?send=1" method="post">
<label for="heading">Überschrift</label>
<input name="heading" type="text" style="display:block;" />
<label for="chapter">Kapitel</label>
<input name="chapter" type="number" style="display:block;"/>
<textarea name="textbereich" rows="10" cols="130"></textarea>
<input type="submit" style="display:block;" />
</form>
</div>
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
</div>
</div>
</body>
And this is from my logic.php:
//BEGINNING fetching data / ouput data
if (isset($_GET['read'])) {
$id = "";
$chapter = $_POST['chapter'];
$heading = "";
$textbereich = "";
$error = false;
$errormessage = "Es ist folgender Fehler aufgetreten: ";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
print ("<h2>" . $ergebnis['heading'] . "</h2>");
print ("<p>Kapitel: " . $ergebnis['chapter'] . "</p>");
print ("<pre>" . $ergebnis['content'] . "</pre>");
}
}
//END fetching data/ output data
?>
Solution: I have to store the data in variables and call them on the HTML in the wanted area.
$outputHeading = "";
$outputChapter = "";
$outputContent = "";
if (!$error) {
$statement = $pdo->prepare("SELECT * FROM beitraege WHERE chapter = :chapter");
$result = $statement->execute(array("chapter" => $chapter));
$ergebnis = $statement->fetch(PDO::FETCH_ASSOC);
$outputHeading = $ergebnis['heading'];
$outputChapter = $ergebnis['chapter'];
$outputArticle = $ergebnis['content'];
}
and in HTML:
<div>
<form action="?read=1" method="post">
<input name="chapter" type="number">
<button type="submit">Auslesen</button>
</form>
<h2><?php echo $outputHeading;?></h2>
<h2><?php echo $outputChapter; ?></h2>
<pre><?php echo $outputContent; ?></pre>
</div>
I hope this text area you are getting data and store it into DB,
<textarea name="textbereich" rows="10" cols="130"></textarea>
but when you are fetching from DB your tag should be
<textarea name="textbereich" rows="10" cols="130"><?php echo $value; ?></textarea>
so that the value will be populated in text Area

Why is my form not working using POST method?

I have written the below HTML code:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
My PHP code:
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
?>
Every time I refresh the page, it only shows the form and "GOODBYE" and does not even insert the data into database table.
Help me out please.
Is it still showing 'GOODBYE' now you've changed
$_POST['add_blog']
to
$_POST['add']
when you click submit?
You have few mistakes,
1) should be: $_POST['add'] instead of $_POST['add_blog']
2) don't have $_POST['blog_cat_id'] as not in form
EDIT
Copied your code and made some changes:
code:
if(isset($_POST['add'])){
print_r($_POST);
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
echo "inside condition";
$insert_blog = "insert into blog values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
else{
echo "GOODBYE";
}
HTML:
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
output
Array ( [title] => test [brief_text] => test [blog_cat_id] => 1 [text] => testing [add] => Add )
inside condition
Now, check your query if doesn't work.
Hope this will help you.
Your query is wrong, columns are not specified and you are open to sql injection you should learn to use parameterized query. but for this time you can use the following.
Try this:
htmlcode
<form action="index.php" method="POST">
<input type="text" name="title" required>
<input type="text" name="brief_text" required>
<input type="text" name="blog_cat_id" required>
<textarea name="text" required></textarea>
<input type="submit" name="add" value="Add">
</form>
index.php
<?php
require_once('db.php');
if(isset($_POST['add'])){
$title = $_POST['title'];
$brief_text = $_POST['brief_text'];
$text = $_POST['text'];
$blog_cat_id = $_POST['blog_cat_id'];
if($title AND $brief_text AND $text AND $blog_cat_id){
$insert_blog = "insert into blog('col1','col2','col3','col4','col5','col6') values ('','$title','$brief_text','$text','$blog_cat_id',NOW())";
$run_insertion = mysqli_query($con, $insert_blog);
if($run_insertion){
echo "Blog has been added!";
}
else{
echo "Error adding blog!!!";
}
}
else{
echo "All fields are required!";
}
}
?>
Note : col1, col2, col3, col4, col5 and col6 will be your column name.

Data ain't changed after submitted to mysql

i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.

PHP - editing data in db issue

I'm going to keep it short and simple. I'm writing a really basic code in php which adds content to mysql db and I've run into an issue with editing. This is my form:
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
And this is my editIt.php
//session start and stuff
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_STRING) == "POST")
{
echo "<script type='text/javascript'>alert('EDITIT!');</script>";
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("WebSiteDB") or die ("Cannot connect to database");
$id = $_POST['id'];
$details = mysql_real_escape_string($_POST['details']);
$time = strftime("%X");
$date = strftime("%B %d, %Y");
$isPublic = 'no';
foreach($_POST['public'] as $eachCheck)
{
if($eachCheck != NULL)
$isPublic = "yes";
}
mysql_query("UPDATE list SET details='$details', dateEdited='$date', timeEdited= '$time', public='$isPublic' WHERE id='$id'");
header("location: home.php");
}
I can't really find an issue with this code (which is not really strange, I'm a newbie at web stuff) and yet it just goes to home.php and does not change data in DB. Please, help me jump this ledge, so I can go on with my life.
I think, the problem is in this line $id = $_POST['id'];. On form submit, the input field value will only be submitted, not the DIV value.
So, please change from :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<div name="id"> '. $id . '</div>
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}
To :
if($idExists)
{
Print '
<form action="editIt.php" method="POST">
<input type="hidden" name="id" value="' . $id . '">
Enter new detail: <input type="text" name="details"/><br/>
public post? <input type="checkbox" name="public[]" value="yes"/><br/>
<input type="submit" value="Update List"/>
</form>
';
}

Categories