Jump to content

Recommended Posts

I'm a beginner with php, but I have a few nifty things working, and I'm trying to enhance my project to do something at the next level.  The project is a library database search tool, and I'm having trouble getting from the search results to the page which shows a record for an individual book.  The search tool works well, and works a few different ways, so I feel I should be able to get this, but this is a first attempt. 

 

I'm stuck on where and how to use $_GET.  If I understand what I need to do, it's something like this:

 

My search results page has a link as part of the last column:

 

201409201.jpg

 

 

My first question is, how do I parse this link in php so that it pulls the Id. number from the database, (so that "Link" points to /book.php?0140441638 as a uri?  That column looks something like this:

 

201409202.jpg

 

On the next page, (book.php) which should be the page which shows the information for the individual book, after connecting to my database I have $query="SELECT * FROM MyTable WHERE id='0140441638'".  How would I go about passing the '0140441638' from the referring link?

 

201409203.jpg

 

The next question is how to concatenate this with the openlibrary link in the screenshot -- so that it is passed like src='..//covers.openlibrary.org/b/isbn/**RESULT**-L.jpg' />

 

Thank you to anyone who can help me with this!

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/291210-passing-to-_get-beginner-question/
Share on other sites

To incorporate a GET variable, the link can be modified as follows:

 

<a href='/book.php?result=$result[24]'>Link</a>

 

Then in book.php, the ID would be retrieved with $_GET['result']. More information about GET variables can be found here:

http://php.net/manual/en/reserved.variables.get.php

For me, the best teacher is an example.

 

Try out the following script.  Submit the form and click the links.  See what happens when you follow the name with square brackets.

 

You are correct in your use of GET.  Typically, you want to use GET when you are getting something from the server, and POST when you are changing something on the server.

<?php
$url=htmlspecialchars($_SERVER['PHP_SELF']);

echo("GET:<pre>".print_r($_GET,1)."</pre>
    POST:<pre>".print_r($_POST,1)."</pre>
    <hr>

    <form action='{$url}' method='post'>
    <input name='p1' type='text' value='value for p1' />
    <input name='p2' type='text' value='value for p2' />
    <input name='p3' type='text' value='value for p3' />
    <input name='p_array[]' type='text' value='value for p1_array' />
    <input name='p_array[]' type='text' value='value for p2_array' />
    <input name='p_array[]' type='text' value='value for p3_array' />
    <input name='submit' type='submit' value='SUBMIT' />
    </form>
    <ul>
    <li><a href='{$url}?g1=123&g2=321'>link 1</li>
    <li><a href='{$url}?g_array[]=123&g_array[]=321'>link 1</li>
    </ul>");
?>

For better assistance please paste your chunks of code in the code tags here versus an image

 

cyberRobot already showed you how to create the hyperlink

To use a $_GET in a query:

//check if result exists in url and is not blank
if(isset($_GET['result']) && trim($_GET['result']) != ''){
$get_result = trim($_GET['result']);//use the trimmed result and create a variable

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$query-"SELECT * FROM MyTable WHERE id='" . mysql_real_escape_string($get_result) . "'";

$resource = mysql_query($query,$link);

if(!$resource){
die('Could not get data: ' . mysql_error());
}

echo "<table class='sortable' align='center' border='0' width='100%'>";

while($result=mysql_fetch_assoc($resource)){
$id = $result['id'];
//$title = $result['title'];

echo "<tr><img align='center' src='http://covers.openlibrary.org/b/isbn/".$id."-L.jpg'/></tr>";
}

echo "<tr><td> </td></tr></table>";

mysql_close($link);
} else {
//show an error, redirect, anything you desire
die('result is not set in url');
}

Some beginner advice for you or anyone else reading this:

 

always try to remove any whitespace

trim()

 

trim an array

$array = array_map('trim', $array);

or

foreach($array as $key => $val){
    $array[$key] = trim($val);
}

mysql_* functions are deprecated, you should use PDO or mysqli_* functions

 

if is a certain type of data you expect check for that
all numbers ctype_digit()
all numbers including decimals is_numeric()

alphanumeric character ctype_alnum()

so on

 

I will refer to the mysqli counterpart functions, mysql and mysqli don't mix

mysqli_fetch_assoc() Returns an associative array that corresponds to the fetched row or NULL if there are no more rows.

mysqli_fetch_row() Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in result set.

mysqli_fetch_array() Returns an array that corresponds to the fetched row or NULL if there are no more rows for the result set represented by the result parameter.

 

Note:

mysqli_fetch_array() returns an array with both the contents of mysqli_fetch_row and mysqli_fetch_assoc merged into one. It will both have numeric and string keys. If do not need both sets, use mysqli_fetch_assoc() instead.

 

Always filter,escape,sanitize anything before you insert into a database, make it exactly how you expect

Validation filters

Sanitize filters

url functions and rawurldecode()

 

mysqli_real_escape_string()

htmlspecialchars()

htmlentities()

 

 

language encoding

multibyte language encoding

iconv

setting database collation and character sets (I use utf8)

 

Am sure I missed some things, these were the top of my head

Another thing, using wildcard * to select items in a query

 

insead of:

$query-"SELECT * FROM MyTable WHERE id='" . mysql_real_escape_string($get_result) . "'";

can just grab only what you need

$query-"SELECT id,title FROM MyTable WHERE id='" . mysql_real_escape_string($get_result) . "'";

This is all enormously helpful - thank you!

When I think it through again, I can see that the first section of the page probably doesn't need to make a server connection.  It just needs to get the variable from the url, and pass it to the openlibrary api url. 

 

The second part of the page needs to make a server connection and sql query to return a number of variables about the book in question, like author, language, pages, etc.

 

I worked with what you graciously posted, and got the second part working, but the first section isn't working.  It gives me the error: ""Could not get data: Query was empty"

 

Using:

mysql_real_escape_string($get_result) 

...is working in my second table td below, but not in the first, and I don't see what I am doing wrong:

<table align="center" border=\"0"\ width=\"100%"\ cellpadding="20" >
		<tr>
			<td>
			  <?php

				//check if result exists in url and is not blank
				if(isset($_GET['result']) && trim($_GET['result']) != ''){
				$get_result = trim($_GET['result']);//use the trimmed result and create a variable

				$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');				if (!$link) {
					die('Could not connect: ' . mysql_error());
				}

				$query-"SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";

				$resource = mysql_query($query,$link);

				if(!$resource){
				die('Could not get data: ' . mysql_error());
				}

				while($result=mysql_fetch_assoc($resource)){
				$ref = $result['ref'];
				//$title = $result['title'];

				echo "<img align='center' src='http://covers.openlibrary.org/b/isbn/".$ref."-L.jpg'/>This";
				}
				mysql_close($link);
				} else {
				//show an error, redirect, anything you desire
				die('result is not set in url');
				}
			  ?>
			</td>		
			<td>
			  <?php 
				$link=mysql_connect("localhost", "mysql_user", "mysql_password") or die("Cannot connect to the database");
			
				mysql_select_db("MyDatabase",$link) or die ("Cannot select the database");
				$query="SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";
				
				 $resource=mysql_query($query,$link);
				 echo "
				 <table class=\"sortable\" align=\"center\" border=\"0\" width=\"100%\">	 ";
				 while($result=mysql_fetch_array($resource))
				 { 
				 echo "<tr><h2>".$result[1]." </h2></tr><tr><td><b>Author:</b></td><td>".$result[8]."</td></tr><tr><td><b>Total Pages:</b></td><td>".$result[15]."</td></tr><tr><td><b>Publisher:</b></td><td>".$result[10]."</td></tr><tr><td><b>ISBN:</b></td><td>".$result[3]."</td></tr><tr><td><b>Binding:</b></td><td>".$result[12]."</td></tr><tr><td><b>Publication Year:</b>   </td><td>".$result[9]."</td></tr><tr><td><b>Language:</b></td><td>".$result[16]."</td></tr><tr><td><b>Genre:</b></td><td>".$result[17]."</td></tr><tr><td><b>KML Code:</b></td><td>".$result[18]."</td></tr><tr><td><b>Id. #:</b></td><td>".$result[0]."</td></tr><tr><td><b>Location:</b></td><td>".$result[21]."</td></tr>";
				 } echo "<tr><td> </td></tr></table>";
			  ?>
			</td>
		</tr>
	</table>

Thank you, again, for any help anyone can offer!

Try changing this:

$query-"SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";

To this:

$query = "SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";

Also, I would highly recommend moving your database connection script to its own file. Then whenever a database connection is required, you just need to import the script using a require (http://php.net/manual/en/function.require.php) or a require_once statement (http://php.net/manual/en/function.require-once.php).

 

Importing the database connection script make it so you'll only need to change the log-in credentials in one spot. Otherwise, you'll need to update every script that uses the database.

 

 

And in case you're not aware, the mysql_* functions have been deprecated. At some point in the near future, you'll need to switch to PDO or MySQLi. More information can be found here:

http://php.net/manual/en/mysqlinfo.api.choosing.php

Success -- my many thanks!   And now I'd like to try to import the connection script as recommended (...and change some of the wildcard queries... and revise with mysqli...)  Here's my attempt at that in /inc/req.php:

<?php 
$db_conx = mysqli_connect("xxxxx", "xxxxx", "xxxxx", "xxxxx");

if (mysqli_connect_errno()) {
	echo mysqli_connect_error();
	exit();
}
?>

...and in my book.php page I have tried both:

require('inc/req.php');

...and:

include('inc/req.php');

...but I'm getting these errors, (using any of include, include_once, require, and require_once):

Warning: include_once(inc/req.php) [function.include-once]: failed to open stream: No such file or directory in /home/content/(...etc)

Warning: include_once() [function.include]: Failed opening 'inc/req.php' for inclusion (include_path='.:/usr/local/php5/lib/php') in /home/content/(...etc)

Where should I have the require(); or the include(); line?  Thank you, again, for any help.

I've placed the req.php file in a few places to make sure it can find it (!), and now I am seeing a different error:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) in /home/content/.../book.php on line 66

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /home/content/.../book.php on line 66

Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/content/.../book.php on line 68
Could not get data: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

...which tells me I must have something wrong here:

(ln66, ln68 are here to show line numbers in the errors. "MyTable" is the actual table in my copy!)

<?php
	require('req.php');
	//check if result exists in url and is not blank
	if(isset($_GET['result']) && trim($_GET['result']) != ''){
	$get_result = trim($_GET['result']);//use the trimmed result and create a variable
			    
(ln66) $query = "SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";

(ln68) $resource = mysql_query($query,$link);

	if(!$resource){
	die('Could not get data: ' . mysql_error());
	}

	while($result=mysql_fetch_assoc($resource)){
	$ref = $result['ref'];
	//$title = $result['title'];

	echo "<img align='center' src='http://covers.openlibrary.org/b/isbn/".$ref."-L.jpg'/>";
	}
	mysql_close($link);
	} else {
	//show an error, redirect, anything you desire
	die('result is not set in url');
	}
?>

Do I need to have this somewhere?

mysql_select_db("MyDatabase",$link) or die ("Cannot select the database");

Everything is working when I call the database from within the page, (with the above mysql_select_db), but I'm not having luck with referenced req.php yet...

Edited by Sigg

Well, I have the connection script working (success!).  Now I'm trying to clean up the fact that I had php in both <td>s.  My first attempt is giving me a new error.

 

Here's the new page attempt:

<table align="center" border=\"0"\ width=\"100%"\ cellpadding="20" >
		<tr>
			<td>
			  <?php
			  
				include('inc/req.php');
				include('inc/bank.php');
				
				if(isset($_GET['result']) && trim($_GET['result']) != ''){
				$get_result = trim($_GET['result']);
			    
				$query = "SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";

				$resource = mysql_query($query,$link);

				if(!$resource){
				die('Could not get data: ' . mysql_error());
				}

				while($result=mysql_fetch_assoc($resource)){
				$ref = $result['ref'];
				//$title = $result['title'];

				echo "<img align='center' src='http://covers.openlibrary.org/b/isbn/".$ref."-L.jpg'/>";
				}
				
				echo "</td><td>"
			  	
		                //Line 85:	
                                $query = "SELECT * FROM MyTable WHERE ref='" . mysql_real_escape_string($get_result) . "'";
				
				$resource=mysql_query($query,$link);
				echo "
				<table class=\"sortable\" align=\"center\" border=\"0\" width=\"100%\">	 ";
				while($result=mysql_fetch_array($resource))
				{ 
				echo "<tr><h2>".$result[1]." </h2></tr><tr><td><b>Author:</b></td><td>".$result[0]."</td></tr><tr><td><b>Location:</b></td><td>".$result[21]."</td></tr>";
				} echo "<tr><td> </td></tr></table>";
				
				mysql_close($link);
				} else {
				die('result is not set in url');
				}
				
			  ?>
			</td>
		</tr>
	</table>

...and here's the error I am receiving:

 Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /home/content/.../book.php on line 85

I commented line 85 into the code above so you can see where there error is.

 

Am I seeing a parse error because of missing punctuation, or is the punctuation correct, but something else is in the wrong place?   Do I need to have the $_GET in there twice?

Edited by Sigg

And just like that - it has come together - Thank you, all who have helped!  And still there is so much more that I hope to do with this project. 

 

For starters, I'm having trouble setting more than one parameter in my query:

$query="SELECT * FROM MyTable WHERE code='GGGGG' or 'HHHHH'";

What do I have wrong here?

 

What do I have wrong here?

 

There is a wrong sql syntax in it. There would be something similar to

$query="SELECT * FROM MyTable WHERE code='GGGGG' or code='HHHHH'"; 

// or much better using IN condition 

$query="SELECT * FROM MyTable WHERE code IN('GGGGG','HHHH')"; 

Note: In SQL, the asterisk or character star (*) symbol is used to indicate that all columns of a table are being referenced.So, it's not recommended of using it, instead you need to specify all of the column names you want to see in the SELECT statement. You could have obtained the same result as the statement using SELECT (*) with something like the following

$query="SELECT col_id, col_name, col_pass, etc.... FROM MyTable WHERE code IN ('GGGG','HHHH')";
Edited by jazzman1

here's a suggestion that hasn't been made yet -

 

you need to separate the php 'business' logic from the 'presentation' logic on the page.

 

the php code that determines what to do on the page and knows how to retrieve the data from the database should all come first. the result of this code should be php variables that provide the input data to the presentation logic.

 

then you put all the presentation logic last. this includes everything from the html doctype tag, through to the closing </html> tag, and any css and javascirpt. the php code/functions/classes in the presentation logic are only that which knows how to take the data it receives from the business logic and produces the output on the page from that data.

 

the business logic contains NO html, css, javascript markup/tags/code. the presentation logic contains NO database specific statements.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.