PHP Simple Search Result - php

I'm a php newbie, and I am having issues getting a search result to return after when trying to get results from an access database. Can anyone spot any glaring issues with the following code? I want it to search the database of books (with author and title in the table) and return the author/book name. Any help is much appreciated! Thanks!
<body>
<div id="wrapper">
<div id="content">
<h1>Search for a book</h1>
<p>You may search by author or title</p>
<form method="post" action="assignment3.php" >
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
<br />
<?php
if(isset($_POST['submit'])){
echo "<h2>Search Results</h2>";
$author=filter_input (INPUT_POST, 'author');
$title=filter_input (INPUT_POST, 'title');
$conn = new COM("ADODB.Connection") or die ("Cannot start ADO");
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="assignment3.mdb"; //connect to database
$conn->open($connString);
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%') OR title LIKE '%".$POST['search']."%'");
if(($search_data)!=0){
$rs=$searchquery;
}
?>
<?php if(($searchquery)!=0) {
do {
echo "<p>'.$author.' ',' '.$title.'</p>";
} while ($rs=($searchquery));
}
else {
echo "No results.";
}
}//end if
?>
</div> <!--end content-->
</div> <!--end wrapper-->
</body>
</html>

First thing is that You are not enclosing the brackets properly. Try Changing
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%') OR title LIKE '%".$POST['search']."%'");
this to
$search_data("SELECT author, title FROM AuthorTitle WHERE author LIKE '%".$_POST['search']."%' OR title LIKE '%".$POST['search']."%'");
And the other thing is that you are not using quotes properly. Change
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="assignment3.mdb";
this to
$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='assignment3.mdb'";
Hope this helps you

Folks - this is the code I used to get it to work:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Book Search</title>
<link href="assignment2.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="content">
<h1>Search for a book</h1>
<p>You may search by author or title</p>
<form method="post" action="" >
<input type="text" name="search">
<input type="submit" name="submit" value="Search">
</form>
<br />
<?php
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$connString= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=e:\\assignment3.mdb";
//creates the connection object and define the connection string
$conn->Open($connString);
$searchquery = filter_input(INPUT_POST, 'search');
$selectCommand="SELECT * FROM AuthorTitle WHERE title LIKE '%$searchquery%' OR author LIKE '%$searchquery%'";
if(isset($_POST['search'])){
$rs = $conn->Execute($selectCommand);
//opens a recordset from the connection object
if (!$rs->EOF){
$selectCommand=$rs->Fields("ProductID");
$author=$rs->Fields("author");
$title=$rs->Fields("title");
echo "<h1>Search Result for '<b>$searchquery</b>':</h1>
<p><b>$title</b>, $author is available for checkout.</p><br />";
}
else
print "No results found.<br /><br />";
$rs->Close;
}
?>
</div> <!--end content-->
</div> <!--end wrapper-->
</body>
</html>

Related

PHP POST requests only inserts blank rows

So i'm pretty new to PHP and can't understand why my POST request is not working. .
I'm just building a simple TodoApp and have a Add new task view like this:
add.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="../css/style.css" />
<title>To-Do List</title>
</head>
<body>
<div class="wrapper">
<form action="" method="post">
<h2 class="title">Add a new task</h2>
<div class="content">
<div class="inputFields">
<label for="task">Task:</label>
<input type="text" name="task" placeholder="Task name" />
<label for="task">Description:</label>
<br />
<textarea type="text" name="description" placeholder="Add a description" rows="5"
cols="40"></textarea>
<br />
<button type="submit" class="btn">Save</button>
</div>
</div>
</form>
<button class="btn">Go back</button>
</div>
</body>
</html>
My db file DB.php looks like this:
<?php
error_reporting (E_ALL ^ E_NOTICE);
/**
* #package DBConnection
* #author Frida
*/
// DB Connection
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=TodoApp', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// GET - Get All tasks
$statement = $pdo->prepare('SELECT * FROM todo_list ORDER BY created DESC');
$statement->execute();
// Fetch all tasks as an assoc array
$tasks = $statement->fetchAll(PDO::FETCH_ASSOC);
// POST - Add a task
$task = $_POST['task'];
$description = $_POST['description'];
$date = date('Y-m-d H:i:s');
$pdo->exec("INSERT INTO todo_list (task, description, status, created)
VALUES ('$task', '$description', 0, '$date')
")
?>
This is my schema:
Todo schema
I've done var_dump($_POST) which shows the array without any issues, if anyone can help me out?
In your HTML form action attribute is empty which mean that form is submit to same file in your case add.php.
So you should use $_POST in add.php file either you must submit form to DB.php for example
<form action="DB.php" method="post">

Data retrieved From MySQL not showing when using PHP

I am working on this program that gets some inputs from the user and then uses that input to retrieve data from a few tables in a MySQL database. My issue is that it seems like I am not getting anything from the MySQL tables, and it would be great if you could help.
dbConn.php
<?php
$ser = "localhost";
$user = "root";
$pass = "pass";
$db = "dbvisual";
$conn = mysqli_connect($ser, $user, $pass, $db) or die("connection failed");
echo "connection success";
?>
form.php
<?php
if(isset($_Post['submit'])){ // Checking to see if the form has been submitted
$battery = (int) $_POST['battery']; // Battery Input element
$cycle = (int) $_POST['cycle']; // Cycle input element
$xVar = $_POST['X']; // X variable
$yVar = $_POST['Y']; // Y variable
// Trying to get the x variable based on what the user said
$mySqlQueryX = "SELECT cap
FROM cycle
WHERE cycleID = $cycle";
$feedbackX = mysqli_query($conn, $mySqlQueryX);
echo "<h1>$feedbackX</h1>";
}
?>
index.php
<!-- Connecting to the database -->
<?php
include 'dbConn.php';
?>
<!-- The Styling of the website -->
<style>
<?php include 'main.css'; ?>
</style>
<!-- The Skeleton of the website -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<?php include "form.php" ?>
<!-- The entire website -->
<div id="body">
<!-- The input half -->
<div id="inputs">
<!-- The input form -->
<form action="index.php" method="POST">
<div id="form">
<!-- Labels -->
<div id="label">
<label for="">Which Batteries?</label>
<label for="">What Cycles?</label>
<label for="">What's X?</label>
<label for="">What's Y?</label>
<label for="">Discharge?</label>
<label for="">Charge?</label>
</div>
<!-- User Info -->
<div id="info">
<input type="text" placeholder="Batteries" required
oninvalid="this.setCustomValidity('No Batteries Were Entered')"
oninput="setCustomValidity('')" name="battery">
<input type="text" placeholder="Cycles" required
oninvalid="this.setCustomValidity('No Cycles Were Entered')"
oninput="setCustomValidity('')" name="cycle">
<select name="X">
<option value="cap">Capacity</option>
<option value="speCap">Specific Capacity</option>
<option value="voltage">Voltage</option>
</select>
<select name="Y">
<option value="cap">Capacity</option>
<option value="speCap">Specific Capacity</option>
<option value="voltage">Voltage</option>
</select>
<input type="checkbox" name="discharge" checked>
<input type="checkbox" name="charge" checked>
</div>
</div>
<!-- Submit Button -->
<div>
<button type="submit" name="submit">Submit</button>
</div>
</form>
</div>
<!-- The graph half -->
<div id="graph">
<p>hello</p>
</div>
</div>
</body>
</html>
When I try to "echo" what I am supposed to get from the database, nothing shows up and I am guessing the issue could be related to mysqli_query() having problems with $conn.
Thank you all!
You need to change your form.php file this is what I propose
<?php
if(isset($_POST['submit'])){
$battery = (int) $_POST['battery']; // Battery Input element
$cycle = (int) $_POST['cycle']; // Cycle input element
$xVar = $_POST['X']; // X variable
$yVar = $_POST['Y'];
$con = mysqli_connect("localhost","root","passer","arduino");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$mySqlQueryX = "SELECT cap
FROM cycle
WHERE cycleID = '".$cycle."' ";
$result = mysqli_query($con, $mySqlQueryX);
// Fetch all
print_r(mysqli_fetch_all($result, MYSQLI_ASSOC));
// Free result set
mysqli_free_result($result);
mysqli_close($con);
}

How do I check which input button has been pressed in PHP?

so I'm new to php and I have two buttons on this html page here (the id value is included in the url):
<!DOCTYPE html>
<head>
<title>StoryBlox is a Social Story Builder Tool</title>
<meta charset="utf-8">
<!-- these support the header/footer formatting -->
<link type="text/css" rel="stylesheet" href="css/main.css">
<link type="text/css" rel="stylesheet" href="css/header_footer.css">
<script src="js/header.js"></script>
<?php //include_once 'confirm_login.php'
include_once 'story_manager.php';
include_once 'open_connection.php';
//include_once 'functions.php';
//sec_session_start();
if(isset($_GET['id'])){
$str_id = $_GET['id'];
$draft_id = get_story_attribute($str_id, 'draft');
}else{
echo "Invalid story id.";
echo "<br>";
}
?>
</head>
<body>
<div id="wrapper_main">
<div id="wrapper_content">
<?php include_once 'header.php'; ?>
<h1>Welcome to StoryBlox Create Story!</h1>
</div>
<!-- menu -->
<!--<div id="inputs"> -->
<form id="create_form" action="save_story.php?id=<?php echo $str_id?>" method="POST">
<input type="text" name="storyTitle" id="title" placeholder="Enter title." autofocus/><br>
<textarea rows="4" cols="50" name="storyDesc" id="description" placeholder="Enter description here."></textarea>
<div id="footer">
<input type="button" name="draftBtn" onclick="this.form.submit()" value="Save as Draft"/>
<input type="button" name="finalBtn" onclick="this.form.submit()" value="Finished!"/>
</div>
</form>
</div>
</div>
<?php include_once 'footer.php'; ?>
</body>
When I click one of these two buttons, I'm brought to this php document here:
include_once 'open_connection.php';
include_once 'story_manager.php';
$mysqli = open_connection();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(isset($_POST['draftBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_GET['id'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
header('Location: createStory.php');
}
elseif(isset($_POST['finalBtn'])){
$title = $_POST['storyTitle'];
$desc = $_POST['storyDesc'];
$str_id = $_POST['storyID'];
update_story_title($str_id, $title);
//update_story_description($str_id, $desc);
save_draft_as_completed($str_id);
header('Location: ../home.php');
}else{ echo "failed";}
}?>
And I always get "failed" printed out on my page. I've been Googling this for hours and I don't understand where I'm going wrong here. If anybody could help that would be appreciated. Also, if anyone could shed some light on what the equivalent to
<input type="textarea">
would be that would be great. Thanks!
Use
<input type="submit" name="draftBtn" value="Save as Draft"/>
instead of the button types with their onclick events.
try to use submit tag instead of button.
and if you want to use button tag then you can pass value through hidden field. set value of hidden field on click event.

my jquery mobile is not working with my php code

Below is my code(jquery mobile and php) I am trying to insert into the database and also echo the following message (pls fill all field and registration complete) that is if the user complete the field or not the following message show display but non of it is working with my jquery mobile code and it is working with my normal site how can I fix this I will appreciate it if you work on my code thank you
<?php
$db= “user”;
$connect = mysql_connect(“localhost“, “alluser”, “six4”)or die(“could not connect”);
Mysql_select_db($db) or die (“could not select database”);
If (isset($_POST['submit'])){
If(empty($_POST['name']) OR empty($_POST['email']) OR empty($_POST['add'])){
$msg = 'pls fill all field';
$name = ($_POST['name']);
$email = ($_POST['email']);
$address = ($_POST['add']);
mysql_query(“INSERT INTO people (Name, Email, Address”) VALUES ('$name, $email, $address')”) or die (mysql_error());
$msg='registration complete ';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<link rel="stylesheet" href="css/jquery.mobile-1.0a1.min.css" />
<script src="js/jquery-1.4.3.min.js"></script>
<script src="js/jquery.mobile-1.0a1.min.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>User</h1>
</div>
<div data-role="content">
<?php echo “$msg”; ?>
<form name=“form” action=“” method=“post”>
<label for=“name”>Name</label>
<input type=“text” name=“name” />
<label for=“email”>Email</label>
<input type=“text” name=“email” />
<label for=“address”>Address</label>
<input type=“text” name=“add” />
<input type=“submit” name=“submit” value=“Submit” />
</form>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
Check your brace positions after your if statements. You check for empty values, but you don't alter the program flow in a meaningful way if you find them.
Also, replace your curly quotes with real quotes. And check for SQL injection. And double-check your MySQL call. You'll get an error from PHP before you'll ever get $msg echoed, based on the way things are written.

Updating a Database With PHP

I'm trying to update my database records with the following code but am having no luck what so ever. Anybody care to help? Thanks
<?php include "base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Project Sproom</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<?php if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
if(!empty($_POST['username']) && !empty($_POST['email']))
{
$newusername = mysql_real_escape_string($_POST['username']);
$newemail = mysql_real_escape_string($_POST['email']);
$edit = mysql_query("UPDATE users (Username, EmailAddress) VALUES('".$newusername."', '".$newemail."') WHERE UserID=".$_SESSION['UserID']."");
// }
?>
<div id="container">
<div id="homemenu">
<ul id="navlist">
<li id="active">Home</li>
<li>Edit Profile</li>
</ul>
</div>
<div id="homemain">
<h1>Edit Profile</h1>
<p>This will be the edit profile when i have figured out how to do it...</p>
<br />
<form method="post" action="profile.php" name="editprofile" id="editprofile">
<label for="username">Username: </label> <input type="text" name="username" id="username" value="<?=$_SESSION['Username']?>"/><br />
<label for="email">E-Mail: </label> <input type="text" name="email" id="email" value="<?=$_SESSION['EmailAddress']?>"/> <br />
<input type="submit" name="editprofile" id="editprofile" value="Submit" />
</fieldset>
</form>
</div>
</div>
<?php
}
else
{
?>
<meta http-equiv="refresh" content="0;index.php">
<?php
}
?>
You're using INSERT syntax for an UPDATE query. The syntax should be like this:
UPDATE users SET Username = 'username', EmailAddress = 'email' WHERE UserID = 1;
Docs here.
You haven't connected to the MySQL database, have you?
I didn't see that in this code...
Or is that part of the included "base.php" on top of this script?
I am afraid you need fist establish a connection to a certain MySQL database before trying to update a row in a table.
Edit:
Okay, well then. Try issue the following line of code after the update:
echo "edit was " .$edit;
This is to check whether the update query was executed successfully (in which case it should echoes true) or failed (in which case it echoes false).
So at least you can tell the result of such a mysql_query.
$edit = mysql_query("UPDATE users SET Username='".$newusername."', EmailAddress='".$newemail."' WHERE UserID=".$_SESSION['UserID']."");
Try this

Categories