PHP & MySQL Novice to Ninja (5th ed), Publishing MySQL Data on the Web (p 130-138)

support
book

#1

Hello!

I'm working my way through the book (5th edition), and was able to successfully connect to my joke database, list the jokes, and add a new joke (p 96-130). When I added the code that would let you delete a joke (p 130-138), rather than display the joke the browser shows:

"Warning: htmlspecialchars() expects parameter 1 to be string, array given in C:\xampp\htdocs\connect\addjoke\jokes.html.php on line 14"

Line 14 is part of the ig (get_magic_quotes_gpc()) section, specifically:

				$process[] = &$process[$key][stipslashes($k)];

I didn't change anything in that section when I added the delete functionality. What did I miss?

<?php

if (get_magic_quotes_gpc())
{
	$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
	while (list($key, $val) = each($process))
	{
		foreach ($val as $k => $v)
		{
			unset($process[$key][$k]);
			if (is_array($v))
			{
				$process[$key][stripslashes($k)] = $v;
				$process[] = &$process[$key][stipslashes($k)];
			}
			else
			{
				$process[$key][stripslashes($k)] = stripslashes($v);
			}
		}
	}
	unset($process);
}

if (isset($_GET['addjoke']))
{
	include 'form.html.php';
	exit();
}

try
{
	$pdo = new PDO('mysql:host=localhost;dbname=ijdb', 'ijdbuser', 'mypassword');
	$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
	$output = 'Unable to connect to the database server.';
	include 'output.html.php';
	exit();
}

if (isset($_POST['joketext']))
{
	try
	{
		$sql = 'INSERT INTO joke SET
			joketext = :joketext,
			jokedate = CURDATE()';
		$s = $pdo->prepare($sql);
		$s->bindValue(':joketext', $_POST['joketext']);
		$s->execute();
	}
	catch (PDOException $e)
	{
		$error = 'Error adding submitted joke: ' . $e->getMessage();
		include 'error.html.php';
		exit();
	}

	header('Location: .');
	exit();
}

if (isset($_GET['deletejoke']))
{
	try
	{
		$sql = 'DELETE FROM joke WHERE id = :id';
		$s = $pdo->prepare($sql);
		$s->bindValue(':id', $_POST['id']);
		$s->execute();
	}
	catch (PDOException $e)
	{
		$error = 'Error deleting joke: ' . $e->getMessage();
		include 'error.html.php';
		exit();
	}

	header('Location: .');
	exit();
}

try
{
	$sql = 'SELECT id, joketext FROM joke';
	$result = $pdo->query($sql);
}
catch (PDOException $e)
{
	$error = 'Error fetching jokes: ' . $e->getMessage();
	include 'error.html.php';
	exit();
}

while ($row = $result->fetch())
{
	$jokes[] = array('id' => $row['id'], 'text' => $row['joketext']);
}
include 'jokes.html.php';
?>

#2

Aaand nevermind. Within minutes of posting this I realized that the error was actually in my jokes.html.php file. I omitted ['text'] from this line:

<p><?php echo htmlspecialchars($joke['text'], ENT_QUOTES, 'UTF-8');?></p>

*facepalm*


#3

It's worth noting that in any PHP version you'll be using these days get_magic_quotes_gpc() will return false and the entire block can be removed. The 6th edition of the book gives a bit more detail on it as well.


#4

Sir I am Reading the Book Novice To Ninja 5th Edition and I m using Xampp..which has PHP & Mysql
But Sir Whenever I tried To Use Including Files as'
include $_SERVER['DOCUMENT ROOT'] .'/includes/filename.inc.php';
it always shows this msg

Notice: Undefined index: DOCUMENT ROOT in C:\xampp\htdocs\Life\Delete Query\index.php on line 2

Notice: Undefined index: DOCUMENT ROOT in C:\xampp\htdocs\Life\Delete Query\index.php on line 51

Notice: Undefined index: DOCUMENT ROOT in C:\xampp\htdocs\Life\Delete Query\index.php on line 68

Please Help Me
Does $_SERVER has removed From the PHP or Nor or Why is this Happening to Me


#5

Hi Englishguru777 welcome to the forum

Try "DOCUMENT_ROOT" with an underscore instead of as two separate words as the array index.

That should get you past the undefined index error.


#6

Thanks Sir But Let Me Tell you After Using
include $SERVER['DOCUMENTROOT'].'/include/filename.inc.php';
Now It is Showing

Warning: include(C:/xampp/htdocs/includes/magicquotes.inc.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Life\Delete Query\index.php on line 2

Warning: include(): Failed opening 'C:/xampp/htdocs/includes/magicquotes.inc.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\Life\Delete Query\index.php on line 2

Warning: include(C:/xampp/htdocs/includes/db.inc.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Life\Delete Query\index.php on line 51

Warning: include(): Failed opening 'C:/xampp/htdocs/includes/db.inc.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\Life\Delete Query\index.php on line 51

Notice: Undefined variable: pdo in C:\xampp\htdocs\Life\Delete Query\index.php on line 55

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\Life\Delete Query\index.php on line 55


#7

<?php
include $_SERVER['DOCUMENT_ROOT'] .'/includes/magicquotes.inc.php';

if(isset($_GET['addjoke']))
{
include 'form.html.php';
exit();
}

if(isset($_POST['joketext']))
{
include $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';

try
{
$sql='INSERT into joke SET joketext=:joketext,jokedate=CURDATE()';
$s=$pdo->prepare($sql);
$s->bindValue(':joketext',$_POST['joketext']);
$s->execute();
}
catch(PDOException $e)
{
$error='Error in Adding New Joke '.$e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}

if(isset($_GET['deletejoke']))
{
include $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
try
{
$sql='DELETE FROM joke WHERE id=:id';
$s=$pdo->prepare($sql);
$s->bindValue(':id',$_POST['id']);
$s->execute();
}
catch(PDOException $e)
{
$error='Error Deleting Joke '.$e->getMessage();
include 'error.html.php';
exit();
}
header('Location: .');
exit();
}

include $_SERVER['DOCUMENT_ROOT'] .'/includes/db.inc.php';
try
{
$sql='SELECT id,joketext FROM joke';
$result=$pdo->query($sql);
}
catch(PDOException $e)
{
$error='Error Fetching Jokes '.$e->getMessage();
include 'error.html.php';
exit();
}

foreach($result as $row)
{
$jokes[]=array('id'=>$row['id'],'text'=>$row['joketext']);
}
include $_SERVER['DOCUMENT_ROOT']. '/includes/jokes.html.php';

This is My Code..,,,

Warning: include(C:/xampp/htdocs/includes/magicquotes.inc.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Life\Delete Query\index.php on line 2

Warning: include(): Failed opening 'C:/xampp/htdocs/includes/magicquotes.inc.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\Life\Delete Query\index.php on line 2

Warning: include(C:/xampp/htdocs/includes/db.inc.php): failed to open stream: No such file or directory in C:\xampp\htdocs\Life\Delete Query\index.php on line 51

Warning: include(): Failed opening 'C:/xampp/htdocs/includes/db.inc.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\Life\Delete Query\index.php on line 51

Notice: Undefined variable: pdo in C:\xampp\htdocs\Life\Delete Query\index.php on line 55

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\Life\Delete Query\index.php on line 55

And I get these Warnings Please Help Me ANyone


#8

include $SERVER['DOCUMENTROOT'].'/include/filename.inc.php';
crrect the path
ex: filname.inc.php is in '/help/include/'
so your code will be
include $SERVER['DOCUMENTROOT'].'/**help**/include/filename.inc.php';
hope this fix the issue


#9

Fatal error: Cannot use isset() on the result of a function call (you can use "null !== func()" instead) in C:\xampp\htdocs\Life\Show Jokes using Template helpers\index.php on line 3

I m receiving this error after using the following code

<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/includes/magicquotes.inc.php';

if(isset($_GET('addjoke'))
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/ form.html.php';
exit();
}

if(isset($_POST['joketext']))
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql='INSERT INTO joke SET joketext=:joketext';
$s=$pdo->prepare($sql);
$s->bindValue(':joketext',$_POST['joketext']);
$s->execute();
}
catch(PDOException $e)
{
$error='Error Adding new jokes '.$e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}

if(isset($_GET('deletejoke'))
{
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql='DELETE FROM joke WHERE id=:id';
$s=$pdo->query($sql);
$s->bindValue(':id',$_POST['id']);
$s->execute();
}
catch(PDOException $e)
{
$error='Error in Deleting Jokes '.$e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}
header('Location: .');
exit();
}

include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
try
{
$sql='SELECT joke.id,joketext,name,email FROM joke INNER JOIN author ON authorid=author.id';
$result=$pdo->query($sql);
}

catch(PDOException $e)
{
$error='Error Fetching Jokes '.$e->getMessage();
include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
exit();
}

foreach($result as $row)
{
$jokes[]=array('text'=>$row['joketext'],
                           'id'=>$row['id'],         
                            'name'=>$row['name'],
                            'email'=>$row['email'];
                            )
}
include $_SERVER['DOCUMENT_ROOT'].'/includes/jokes.html.php';

#10

Off Topic

@Englishguru777: when you post code on the forums, you need to format it so it will display correctly. (I've edited your post above to format it.)

You can highlight your code, then use the </> button in the editor window, or you can place three backticks ``` (top left key on US/UK keyboards) on a line above your code, and three on a line below your code. I find this approach easier, but unfortunately some European and other keyboards don't have that character.


#11

This is line 3 of your code:

if(isset($_GET('addjoke'))

Look carefully at the types of bracket you are using.


#12

Thank You Bro
i know it was a silly mistake,, But it happens
Thanks Again


#13

Here is my controller code

<?php


//Display Search Form
include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';

try
{
		$result=$pdo->query('SELECT id,name FROM author');
}
catch(PDOException $e)
{
	$error='Error Fetching Author Details '.$e->getMessage();
    include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
    exit();
}

foreach($result as $row)
{
	$authors[]=array('id'=>$row['id'],'name'=>$row['name']);
}

try 
{
	$result=$pdo->query('SELECT id,name FROM category');
}
	
catch(PDOException $e)
{
	$error='Error Fetching Category Details '.$e->getMessage();
	include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
	exit();
}

foreach($result as $row)
{
$categories[]=array('id'=>$row['id'],'name'=>$row['name']);	
}
include 'searchform.html.php';
 
 
if (isset($_GET['action']) and $_GET['action']=='search')
{
	include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
	
//The Basic SELECT Statement
	$select='SELECT id,joketext';
	$from=' FROM joke';
	$where=' WHERE TRUE';
	
	$placeholders[]=array();
	
	if($_GET['author'] !='') //An Author is Selected
 	{
	$where .=" AND authorid=:authorid";
    $placeholders[':authorid']=$_GET['author'];	
	}
	
	if($_GET['category'] !='') //A Category is Selected
	{
		$from .=" INNER JOIN jokecategory ON id=jokeid";
	    $where .=" AND categoryid=:categoryid";
		$placeholders[':categoryid']=$_GET['category'];
	}
	
	if($_GET['text'] !='') //Some Search Text Was Specified
	{
	$where .=' AND joketext LIKE :joketext';
	$placeholders[':joketext']='%'.$_GET['text'].'%';		
	}

	try{
		$sql=$select . $from . $where;
		$s=$pdo->query($sql);
		$s->execute($placeholders);
	   }
		
	catch(PDOException $e)
	{
		$error='Error Showing Jokes related to Search criterian '.$e->getMessage();
		include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
		exit();
	}

	foreach($s as $row)
	{
		$jokes[]=array('id'=>$row['id'],'text'=>$row['joketext']);
	}
include 'jokes.html.php'; 
exit();
    }
	?>

And this is my jokes.html.php file

<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/helpers.inc.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage Jokes</title>
</head>
<body>
<h1>Search Results</h1>
<?php if(isset($jokes)):?>
<table>
   <tr><th>Joke Text</th><th>Options</th></tr>
   <?php foreach($jokes as $joke): ?>
   <tr><td><?php htmlout($joke['text']);?></td>
   <td>
       <form action="?" method="post">
	     <div>
	      <input type="hidden" name="id" value="<?php htmlout($joke['id']); ?>">
	      <input type="submit" name="action" value="Edit">
          <input type="submit" name="action" value="Delete">
         </div>
     </form> 
   </td>
  </tr>  
 <?php endforeach;?>
 </table>
 <?php endif; ?>
 
 <p><a href="?">New Search</a></p>
 <p><a href="..">Return to JMS</a></p>
 
 </body>
 </html>

and here is my searchform.html.php

<?php include $_SERVER['DOCUMENT_ROOT'].'/includes/helpers.inc.php';?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Manage jokes</title>
</head>
<body>
<h1>Manage Jokes</h1>
<p><a href="?add">Add a New Joke</a></p>

<form action="" method="get" >
<p>View Jokes satisfying the Following Criteria</p>
<div>
  <label for="author">By Author:</label>
  <select name="author" id="author">
     <option value="">Any Author</option>
  
     <?php foreach($authors as $author):?>
     <option value="<?php htmlout($author['id']); ?>"><?php htmlout($author['name']);?></option>
     <?php endforeach; ?>
  
  </select>
</div>

<div>
     <label for="category">By Category:</label>
	 <select name="category" id="category">
	    <option value="">Any Category</option>
	   <?php foreach($categories as $category): ?>
	     <option value="<?php htmlout($category['id']); ?>"><?php htmlout($category['name']);?> </option>
	   <?php endforeach; ?>
     </select>
</div>	


<div>
    <label for="text">Containing Text:</label>
	 <input type="text" name="text" id="text" >
</div>

<div> 
    <input type="hidden" name="action" value="search">
    <input type="submit" value="Search"> 
</form>
<p><a href="..">Return to JMS Home</p>
</body>
</html>

& whenever I try to run this code I got the searchform and when I choose any category and then click Search I got this Error
Error Showing Jokes related to Search criterian SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':categoryid' at line 1

& whenever I try to run this code I got the searchform and when I choose any author and then click Search I got this Error
Error Showing Jokes related to Search criterian SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':authorid' at line 1

and in case of searching via some text i got this
Error Showing Jokes related to Search criterian SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':joketext' at line 1

What to do now I have checked my code many times with the code archive and it is all same

And the funny thing is I received this error as links on clicking these links get me back on my JMD


#14

This

$sql=$select . $from . $where;
$s=$pdo->query($sql);
$s->execute($placeholders);

isn't the correct way to prepare and execute a prepared statement in PDO. You need to call prepare() first, and then call execute(). When you call query() like this, it will try to run the query with your placeholders, which will be giving you the syntax error.


#15

A very special Thanks to you Sir


#16

Whenever we define an array we use this kind of statement

$myarray=array();

and after we defined the array we can assigned values to it
like

$myarray[]='John';

but in this case

while($row=$result->fetch())
{
$jokes[]=$row['joketext'];
}

we are directly assigning values without defining the array

can someone please explain


#17

Are you certain the array isn't defined in an include / require ?

I usually do $some_arr = []; instead of $some_arr = array(); but anyway, if the array is getting used later on and the fetch fails for some reason it's an unpleasant error waiting to happen.


#18

Are you certain the array isn't defined in an include / require?

yes totally


#19

Try setting the following and both errors and warnings will be displayed:

<?php
declare( strict_types=1,);
ini_set('display_errors', 'true'); // ONLY FOR DEVELOPING OTHERWISE FALSE
error_reporting(-1); // MAXIMUM ERROR AND WARNINGS

// Your script goes here

Errors and warnings should all be logged in:

ini_get('error_log');


#20

From the Manual (with my bold)

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.