Jump to content

dudleylearning

Members
  • Posts

    27
  • Joined

  • Last visited

Posts posted by dudleylearning

  1. Hi,

     

    I am in the process of creating a search on my website. It has two search criteria (joke_text as a text field and author as a list box). When I try to search using just the joke_text field it presents no data. But when I add data to both joke_text and author the search presents the correct data. It also works when I select just an author. Here is a snippet of the code that I have used: 

     
    <div>
    			<form action="search.php" method="POST">
                <div class="control-group">
    				<label class="control-label">Joke</label>
    				<div class="controls">
    					<input type="text" name="text" id="text">
    				</div>
    			</div>
                    
    				<div class="control-group">
    				<label class="control-label">Author</label>
    				<div class="controls">
    				  <label for="author">author</label>
    				  <select name="author" id="author">
    				    <option>select</option>
    				    <option value="1">1</option>
    				    <option value="2">2</option>
    				    <option value="3">3</option>
    			      </select>
    				</div>
    			</div>
                    
                    
                    <button type="submit" class="btn btn-orange">Go</button>
    			</form>
    		</div>
    		
    		<?php
    			# retrieve text from search field
    			if (!empty($_GET['text']) || !empty($_POST)) {
    				$joke_text_search = $_REQUEST['text'];
    				$joke_text_search_filter = str_replace(array('%', '_'),'\\',$joke_text_search);
    				$joke_text = '%' . $joke_text_search_filter . '%';
    				
    				$author_select = $_REQUEST['author'];
    				$author = '%' . $author_select . '%';
    				
    				$search  = $dbConnection->prepare("SELECT * FROM joke WHERE author_id LIKE ? AND joke_text LIKE ?");
    				$search->execute([$author, $joke_text]);
    				$result = $search->fetchAll(); 

    Could someone take a look and give me some guidance to what I should be looking at  :happy-04:

     

  2.  

    Yes, but you also need to understand what to replace the percent character with. Right now, you're replacing it with an underscore which stands for “exactly one arbitrary character”. Obviously that doesn't help.

     

    If you want percent characters to be interpreted literally, you need to escape them with backslashes:

    $search = '%'.str_replace('%', '\\%', $_GET['text']).'%';
    

     

    that worked like a charm, exactly what I wanted. thanks Jacques1.

  3. Of course it does. "%" is the wildcard character which matches anything.

     

    It's like searching a directory for *.* - you get all the files.

     

    ok, didn't know that. thanks for the tip. I tried it in another commercial website and it gave all the data  :happy-04:

  4. Hi,

     

    so I've had an attempt at creating a search form I can get data from it so that's a positive. This is the relevant snippet:

    $joke_text_search = $_REQUEST['text'];
    $joke_text = '%' . $joke_text_search . '%';
    $search  = $dbConnection->prepare("SELECT * FROM joke WHERE joke_text LIKE ?");
    $search->execute([$joke_text]);
    $result = $search->fetchAll();	
    

    but if I type in % it shows all the data. Having a read of the PHP manual, seems that I should use str_replace. I have had an attempt with it but the % symbol still shows all the data:

    $joke_text_search = $_REQUEST['text'];
    $joke_text_search_filter = str_replace(array('%','_'),'',$joke_text_search);
    $joke_text = '%' . $joke_text_search_filter . '%';
    $search  = $dbConnection->prepare("SELECT * FROM joke WHERE joke_text LIKE ?");
    $search->execute([$joke_text]);
    $result = $search->fetchAll(); 

    Could someone lend a hand?

     

  5. nevermind, I figured it out :)

     <select name="author_id" id="author_id">
     <option value="">Select one</option>
    <?php 
    $sql2 = 'SELECT id, name FROM author';
    foreach ($dbConnection->query($sql2) as $data2) { ?>
    <option value="<?php echo $data2['id']; ?>" 
    <?php if($data['author_id'] == $data2['id']) 
    { echo 'selected'; } ?>>
    <?php echo $data2['name']; ?>
     </option>
    <?php } ?>
    </select>
    
  6. Hi All,

    I have redeveloped my code, but I have come to a problem in getting the listbox to echo the data retrieved from the database.

     

    I have two tables which hold the data:

    TABLE joke (id, joke_text, joke_date, author_id)
    TABLE author(id, name, email)
    

    This is what I have attempted so far:

    <?php 
    # display all php errors
    error_reporting(-1);
    ini_set('display_errors', 1);
    
    # include dbConnection details
    require '../includes/dbconn.php';
    
    	# initially set $id to empty
    	$id = null;
    	
    	# if $id is not empty, GET the id
    	if ( !empty($_GET['id'])) {
    		$id = $_REQUEST['id'];
    	}
    	
    	# if $id is empty then send the user back to index.php
    	if ( null==$id ) {
    		header("Location: index.php");
    		exit();
    	}
    	
    	if ( !empty($_POST)) {
    		// keep track validation errors
    		$joke_textError = null;
    		$authorError = null;
    		
    		// keep track post values
    		$joke_text = $_POST['joke_text'];
    		$author_id = $_POST['author_id'];
    		
    		// validate input
    		$valid = true;
    		if (empty($joke_text)) {
    			$joke_textError = 'Please enter joke text';
    			$valid = false;
    		}
    		
    		
    		// update data
    		if ($valid) {
    			$sql = "UPDATE joke set joke_text = ?, author_id = ? WHERE id = ?";
    			$update = $dbConnection->prepare($sql);
    			$update->execute(array($joke_text,$author_id,$id));
    			header("Location: index.php");
    			exit();
    		}
    	} else {
    		$sql = "SELECT id, joke_text, joke_date, author_id
    				FROM joke  
    				WHERE id = ?";
    		$select = $dbConnection->prepare($sql);
    		$select->execute(array($id));
    		$data = $select->fetch();
    		$joke_id = $data['id'];
    		$joke_text = $data['joke_text'];
    		$joke_date = $data['joke_date'];
    			}
    ?>
    
    [display of joke_text div]
    
    <select name="author_id" id="author_id">
    <option value="">Select one</option>
    <?php 
    	$sql2 = 'SELECT id, name FROM author';
    	foreach ($dbConnection->query($sql2) as $data2) { ?>
    	<option value="<?php echo $data2['id']; ?>" 
    		<?php if(isset($_POST['author_id']) && 
    		($_POST['author_id'] == $data['author_id'])) 
    		{ echo 'selected'; } ?>>
    		<?php echo $data2['name']; ?>
    	</option>
    	<?php } ?>
    </select>
    
    
    

    When I use "inspect" from Chrome, it populates the listbox with all the authors in HTML, but can't figure how to retrieve the current author. Any suggestions? 

  7. Hi All,

     

    which is the better way to do the database connection:

    <?php
    # display all php errors
    error_reporting(-1);
    ini_set('display_errors', 1);
    
    try
    {
    	$dbConnection = new PDO('mysql: host=localhost; dbname=jokesdb', 'root', 'password');
    	$dbConnection -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    	$dbConnection -> exec('SET NAMES "utf8"');
    }
    catch (PDOException $e)
    {
    	$status = 'Unable to connect to the database server.' . '<br />' . $e -> getMessage();
    	include 'status.php';
    	exit();
    }
    
    $status = 'Database connection established';
    include 'status.php';
    ?>
    

     

     

    or is it better to use:

    <?php
    	# display all php errors
    	error_reporting(-1);
    	ini_set('display_errors', 1);
    
    	$host = 'localhost';
    	$database   = 'db';
    	$username = 'root';
    	$password = 'password';
    	$charset = 'utf8';
    	$option = array(
    		PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    		PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    	);
    	
    	$dataSource = 'mysql:host=' . $host . ';dbname=' . $database . ';charset=' . $charset;
    	$dbConnection = new PDO($dataSource, $username, $password, $option);
    ?>
    

    Thoughts?

  8. How are you expecting to get the ID when the form first loads? Are you clicking an "Edit" link? 

     

    ok, forgot to post that one. There is a link for the user to click on from index.php which then opens the edit page:

    <form action="edit_author.php" method="post">
    <input type="hidden" name="id" value="<?php echo $data['id']; ?>">
    <input type="submit" value="Edit">
    </form>
    
  9. Hi All,

     

    I'm having a go at making an edit page and have come across a slight problem. I get this error on the edit page when the submit button is pressed:

    Notice: Undefined index: id 

    this is the script that I have attempted:

    <?php
    # display all php errors
    error_reporting(-1);
    ini_set('display_errors', 1);
    
    # include dbConnection details
    include '../includes/dbconn.php';
    
    # set form input fields
    $sql = 'SELECT id, name, email FROM author WHERE id = :id';
    $query = $dbConnection->prepare($sql);
    $query->bindValue(':id', $_POST['id']);
    $query->execute();
    $row = $query->fetch();
    $name = $row['name'];
    $email = $row['email'];
    $id = $row['id'];
    
    # if the form has been posted
    if (isset($_GET['update_details']))
    {
    	$sql = 'UPDATE author SET
    	name = :name,
    	email = :email
    	WHERE id = :id';
    	
    	$query = $dbConnection->prepare($sql);
    	$query->bindValue(':id', $id);
    	$query->bindValue(':name', $_POST['name']);
    	$query->bindValue(':email', $_POST['email']);
    	$query->execute();
    	
    	$message = 'Author details successfully updated';
    	header('Location: index.php?message=' . $message);
    }
    ?>
    

    the error makes reference to this line:

    $query->bindValue(':id', $_POST['id']);
    

    I can't see where I have gone wrong with it. Any tips on what I should be looking at?

  10. Hi All,

     

    couldn't seem to figure how to pass data from page 2 to page 1. On page 2 I have this code block:

    # if the form has been posted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
    	# check for empty fields
    	if (!empty(trim(($_POST['name'] == ''))))
    	{
    		$nameErr = "<span class=\"error\">Name is required</span>";
    	}
    	if (!empty(trim(($_POST['email'] == ''))))
    	{
    		$emailErr = "<span class=\"error\">Email is required</span>";
    	}
    	 
    	# if all is fine, then add data to the database
    	else 
    	{
    		$sql = 'INSERT INTO author SET
    		name = :name,
    		email = :email';
    		
    		$query = $dbConnection -> prepare($sql);
    		$query -> bindValue(':name', $_POST["name"]);
    		$query -> bindValue(':email', $_POST["email"]);
    		$query -> execute();
    		
    		$message = 'done';
    		header('Location: index.php');
    		
    	}
    }
    

    The variable $message I wanted to pass to page 1, where I have this in:

    <?php if(isset($_POST['message'])) { echo $_POST['message']; } ?>
    

    I can't seem to figure out the problem? Any tips?

     

    Thanks

  11. i've tried to take into account your point:

    <label for="author">Author:</label>
    <select name="author" id="author">
    	<option value="">Select one</option>
    	<?php foreach ($authors_in_db as $data): ?>
    	<option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>" 
    		<?php if(isset($_POST[$data['id']]) && $_POST[$data['id']] == $data['id']) { echo($data['id']?' selected':'');} ?>>
    		<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
    	</option>
    	<?php endforeach; ?>
    </select>
    

    Surely I'm not that far off now? Anything that you can see that I am missing from it?

  12. I've tried this:

    <label for="author">Author:</label>
    <select name="author" id="author">
    	<option value="">Select one</option>
    	<?php foreach ($authors_in_db as $data): ?>
    	<option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>" selected>
    		<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
    	</option>
    	<?php endforeach; ?>
    </select>
    

    But that selects the last item. Would I need something similar to this:

    <option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>"
    <?php echo($data['name']?' selected="selected"':'');?>>
    <?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
    </option>
    

    ?

  13. Hi,

     

    how do I make the options within the list box sticky:

    <label for="author">Author:</label>
    <select name="author" id="author">
    	<option value="">Select one</option>
    	<?php foreach ($authors_in_db as $data): ?>
    	<option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>">
    		<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
    	</option>
    	<?php endforeach; ?>
    </select>
    

    I've managed to do it with a text area:

    <label for="joke_text">Type your joke here:</label>
    <textarea id="joke_text" name="joke_text" rows="3"><?php if(isset($_POST['joke_text'])) { echo $_POST['joke_text']; }?></textarea>
    
  14. Thank you for replying Physco. I've tried what you have mentioned, to the best of my ability. This is what I have done to the index.php file:

    <?php
    include '../includes/dbconn.php';
    
    # add joke link pressed
    if (isset($_GET['add_joke']))
    {	
    $formErrors = '';
    	// Build the list of authors for drop-down list
    	try
    	{
    		$result = $dbConnection->query('SELECT id, name FROM author');
    	}
    	catch (PDOException $e)
    	{
    		$error = 'Error fetching list of authors.' . '<br />' . $e -> getMessage();
    		include '../includes/error.php';
    		exit();
    	}
    
    	foreach ($result as $row)
    	{
    		$authors_in_db[] = array(
    		'id' => $row['id'], 
    		'name' => $row['name']
    		);
    	}
    	include 'form.php';
    	exit();
    }
    
    # add joke to the database
    if (isset($_GET['add_joke_to_db']))
    {	
    	$formErrors = array();
        if ($_POST['joke_text'] == '')
        {
            $formErrors['joke_text'] = '* Joke text field cannot be empty.';
        }
        if ($_POST['joke_text'] == '')
        {
            $formErrors['author'] = '* Author field cannot be empty.';
        }
    	
    	if (!empty($formErrors)) 
    	{
        include 'form.php';
    exit();
    	} 
    	else 
    	{
    		# continue with adding joke to the database
    		try
    		{
    			$sql = 'INSERT INTO joke SET
    			joke_text = :joke_text,
    			joke_date = CURDATE(),
    			author_id = :author_id';
    			
    			$s = $dbConnection -> prepare($sql);
    			$s -> bindValue(':joke_text', $_POST['joke_text']);
    			$s -> bindValue(':author_id', $_POST['author']);
    			$s -> execute();
    		}
    		catch (PDOException $e)
    		{
    			$error = 'Error adding joke.' . '<br />' . $e -> getMessage();
    			include '../includes/error.php';
    			exit();
    		}
    	
    		header('Location: .');
    		exit();
    	}
    }
    
    # delete joke from the database
    if (isset($_GET['delete_joke']))
    {
    	try
    	{
    		$sql = 'DELETE FROM joke WHERE id = :id';
    		$s = $dbConnection -> prepare($sql);
    		$s -> bindValue(':id', $_POST['id']);
    		$s -> execute();
    	}
    	catch (PDOException $e)
    	{
    		$error = 'Error deleting joke.' . '<br />' . $e -> getMessage();
    		include '../includes/error.php';
    		exit();
    	}
    
    header ('Location: .');
    exit();
    }
    
    # select all jokes from the database
    try
    {
    	$sql = 'SELECT joke.id, joke.joke_text, joke.joke_date, author.name, author.email 
    	FROM joke INNER JOIN author
    	ON author_id = author.id
    	ORDER BY joke.id';
    	$result = $dbConnection -> query($sql);
    }
    catch (PDOException $e)
    {
    	$error = 'Error fetching jokes.' . '<br />' . $e -> getMessage();
    	include '../includes/error.php';
    	exit();
    }
    
    # add each data item within an array
    foreach ($result as $row)
    {
    	$jokes_in_db[] = array(
    	'joke.id' => $row['id'], 
    	'joke.joke_text' => $row['joke_text'], 
    	'joke.joke_date' => $row['joke_date'],
    	'author.name' => $row['name'],
    	'author.email' => $row['email']
    	);
    }
    
    include 'jokes.php';
    ?>
    

    and this to the form.php page:

    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Add Joke</title>
    		<link rel="stylesheet" type="text/css" href="../includes/styles.css" />
    	</head>
    	<body>
    		<h1>Add Joke</h1>
    		<form action="?add_joke_to_db" method="post">
    			<div>
    				<label for="joke_text">Type your joke here:</label>
    				<textarea id="joke_text" name="joke_text" rows="3"></textarea>
    				 <span class="error"><?php echo $formErrors['joke_text'];?></span>
    			</div>
    			<div>
    				<label for="author">Author:</label>
    				<select name="author" id="author">
    					<option value="">Select one</option>
    					<?php foreach ($authors_in_db as $data): ?>
    					<option value="<?php echo htmlspecialchars($data['id'], ENT_QUOTES, 'UTF-8'); ?>">
    						<?php echo htmlspecialchars($data['name'], ENT_QUOTES, 'UTF-8'); ?>
    					</option>
    					<?php endforeach; ?>
    				</select>
    				<span class="error"><?php echo $formErrors['author'];?></span>
    			</div>
    			<div>
                	<input type="submit" value="Add">
                </div>
    		</form>
    	</body>
    </html>
    

    I get the errors shown inline now which is great.

     

    I've seen that I get an additional issue where the author drop-down list is empty when form.php is shown. If I add this before I include form.php:

    try
    	{
    		$result = $dbConnection->query('SELECT id, name FROM author');
    	}
    	catch (PDOException $e)
    	{
    		$error = 'Error fetching list of authors.' . '<br />' . $e -> getMessage();
    		include '../includes/error.php';
    		exit();
    	}
    
    	foreach ($result as $row)
    	{
    		$authors_in_db[] = array(
    		'id' => $row['id'], 
    		'name' => $row['name']
    		);
    	}
    

    it works as expected. But, seeing as it is a repeat of what I have under 

    if (isset($_GET['add_joke']))
    

    how would I go about reusing the command without copying it out again?

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.