PHP - Display MySQL data based on user selection on new page - php

I am trying to display every job record in my database and when a user clicks on a record, it will go on to display the job description for that record on a new page.
At my current state I've managed to display every job, clicking on them will direct the user to the "showjob.php?id=". My problem is that it isn't displaying information for my job.
Page with list of jobs: THIS WORKS
$results = $pdo->query('SELECT * FROM jobs');
foreach ($results as $row) {
echo '<a class="job_listing_href" href="showjob.php?id="' . $row['job_id'] . '><div id="job_listing">' . $row['job_title'] . ' '
. $row['cat_job'] . '</div><br/><br/>';
}
Page with individual job information:
$pkey = mysql_real_escape_string($_GET['job_id']);
$sql = "SELECT * FROM jobs WHERE job_id='$pkey'";
foreach ($results as $pdo) {
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}
It isn't related to my job_desc as I can implement it to my previous page and it lists it just fine. My guess is that it's something to do with my $_GET but not sure.
Also as a sidenote, I'm aware my website is vulnerable to SQL injection, I'm going to fix it soon :)
Can anyone provide a solution or put me on the right tracks?
Thank you to anyone spending the time helping me!
UPDATE
I have took everyone's suggestions - thank you, but my "showjob" page still isn't displaying anything. This is my new code:
$pkey = mysql_real_escape_string($_GET['id']);
$sql = "SELECT * FROM jobs WHERE job_id='$pkey'";
$results = $pdo->query($sql);
foreach($results as $row) {
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}

You're mixing MySQL APIs using mysql_real_escape_string() while being connected using PDO, so you can't use those together while connecting/querying for the same code.
Sidenote: You theoretically could with older versions of PHP, but as of PHP 7.0, the mysql_ API has been removed, so you definitely wouldn't be able to use it here if that were the case.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
"This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0."
What you need to use here is a PDO prepared statement in order to escape the data, which is what you are looking to do here.
$pdo = new PDO("...");
if(!empty($_GET['job_id'])){
$pkey = $_GET['job_id'];
$statement = $pdo->prepare("SELECT * FROM jobs WHERE job_id = :jobid");
$statement->execute(array(':jobid' => $pkey));
while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
// echo $row['field1'].' '.$row['field2']; //etc... taken from an example, sorry.
echo '<div id="job_listing">' . $row['job_title'] . ' ' . $row['cat_job'] . '</div><div id="job_listing_content">' . $row['job_desc'] .
'</div>';
}
}
else{
echo "GET is empty, check for errors.";
}
Also check for errors if you're not already doing so.
References:
http://php.net/manual/en/pdo.error-handling.php
http://php.net/manual/en/function.error-reporting.php
PDO references:
http://php.net/pdo.prepared-statements
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Footnotes:
I noticed you're using href="showjob.php?id yet you're using the $_GET['job_id'] array.
id != job_id.
That will fail you if that's what you're still using and both of those need to match.
Error reporting would have told you about that.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Then the rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Other notes:
If your server does not support the mysql_ MySQL API, then error reporting would have thrown you something similar to the following:
Fatal error: Call to undefined function mysql_real_escape_string()...

The results are not showing because you have your variable names mixed up, see below revision:
Change:
$pkey = mysql_real_escape_string($_GET['job_id']);
to:
$pkey = mysql_real_escape_string($_GET['id']);
Update: You are also missing: $results = $pdo->query($sql);

You are passing the job id parameter as id. However, when fetching the id for the specific job, you're retrieving job_id out of the $_GET superglobal. $_GET['id'] instead of $_GET['job_id']should work.
PS: As Alex pointed out, actually issuing a query via $results = $pdo->query($sql) may also help. Followed by iterating over foreach($results as $row). Although there should only ever be one result ...

seems that
foreach ($results as $pdo) {
echo '<div id="job_listing">' . $row['job_title']
in foreach your are using $pdo name value, but inside using $row, use the same an tell us.
expect it help

Related

Duplicate items in MySQL database after editing code

I have a problem with my PHP code.
I am trying to make a level create function for a small game project me and another person are working on.
My code works.. but generates a lot of duplicates.
Here's the code: (Don't laugh at me for how vulnerable this is, this will be fixed eventually, THIS IS JUST TEST CODE AND WILL NEVER BE ON A PUBLIC SERVER IN ANY CIRCUMSTANCE, OK?)
$mysqli = new mysqli("localhost", "Username", "Password", "sys");
$SqlQuery = "INSERT INTO levels (levelname, levelauthor, leveldata)
VALUES(\"" . $_GET["levelName"] . "\", \"" . $_GET["levelAuthor"] . "\", \"" . $_GET["levelData"] . "\");";
$query2 = "SELECT * FROM levels WHERE leveldata = \"" . $_GET["levelData"] . "\";";
//echo "SELECT * FROM levels WHERE leveldata = \"" + $_GET["levelData"] + "\";";
$uresult = $mysqli->query($SqlQuery, MYSQLI_USE_RESULT);
$res2 = $mysqli->query($query2, MYSQLI_USE_RESULT);
if ($uresult) {
while ($row = $res2->fetch_assoc()) {
//This should always work. Lol
echo "(SUC)|ID:" . $row["levelid"];
}
}
After running this code, I expected to just check my database and be able to see the test I wrote, without duplicates.
I started the PHP development server and went to:
http://localhost/Create.php?levelName=PHPTest&levelAuthor=Test3&levelData=[snip]
I expected to see something along the lines of "(SUC)|ID:4" (there were 3 entries in the database at the time), but I saw this:
(SUC)|ID:4(SUC)|ID:5(SUC)|ID:6(SUC)|ID:7(SUC)|ID:8(SUC)|ID:9(SUC)|ID:10(SUC)|ID:11
This was unexpected. I thought it was just an error in my code (keep in mind, the last one had a broken ID grabbing system, but worked), and that it would work, but then, I went to check the database, and saw a ton of duplicates with the same data.
Does anyone know how to fix this code?
Obvious question but autocommit is enabled on database?
Do you have some open transaction?
Use this to check open transactions on MySQL.

Echoing Out A Mysql Query

Alright. I have searched and searched for an answer, but I just could not find it.
I am writing a simple php script that takes the url information and runs it through a MySQL query to see if a result comes up. I try to echo the variable holding the query out, but nothing shows up. I know there must be a result because if I enter the query manually in MySQL it displays my desired result.
$result = mysqli_query("SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
I have tried to echo out both the $result and $data. But there is nothing displayed. I am so new to programming, and this is my first StackOverflow post, so forgive me if I am making huge errors.
Actually mysqli_query() requires two parameters... check the following sample example ..
<?php
$conn = mysqli_connect('localhost','root','','your_test_db');
$_GET['page'] = 1;
$result = mysqli_query($conn,"SELECT * FROM your_table WHERE id = '" . $_GET['page'] . "'");
$data = mysqli_fetch_assoc($result);
echo ("You have just entered in " . $data['id'] . "!!! YAY");
?>
As you have stated you are just in a learning phase, it is okay to code these sort of queries just to learn yourself but do not code these kind of queries as these queries are vulnerable so i would suggest you to use prepare queries or PDO...
Also never use SELECT * in your queries, this is a bad practice, only deal with the fields which you requires in return.
Also, you can always check whether your database is connected or not. So that you have a better idea.
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
you have not mentioned whether you are following OOP structure or not .. so i would suggest you to check error_reporting() and connect database on the same page to check the things around ..
Also you can check whether you without WHERE condition for now "SELECT * FROM your_table just to make sure whether you are getting atleast all the records or not.
The problem is that you're not setting up the connection in the query. mysqli_query() requires two parameters.
Make the connection first:
$conn = mysqli_connect("localhost", "user", "password", "dbname");
Now execute the query:
$result = mysqli_query($conn,"SELECT * FROM pages WHERE pageq = '" . $_GET['page'] . "'" );
NOTE: Your code is heavily vulnerable to MySQL injections. Use MySQLi or PDO Prepared statements.
Also, you should use mysqli_errno() to find out your query bugs.
Edit:
Also do this:
while($row=mysqli_fetch_assoc($result)){
//do the result output.
}

i am currently have an MYSQL syntax error

i am very new at MYSQL and after i created this script to update a row in the table of a MYSQL Database and run it i get this error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '265'', Employer_VAT_number = ''45698'', Employer_Name = ''Namtax_Ltd'', Employer' at line 3
here is the code
// username and password sent from form
$Numb=$_POST["Numb"];
$VAT=$_POST["VAT"];
$Name=$_POST["Name"];
$Addr=$_POST["Addr"];
$PO=$_POST["PO"];
// To protect MySQL injection (more detail about MySQL injection )
$Numb = stripslashes($Numb);
$VAT = stripslashes($VAT) ;
$Name = stripslashes($Name) ;
$Addr = stripslashes($Addr) ;
$PO = stripslashes($PO) ;
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
$VAT = "'" . mysql_real_escape_string($VAT) . "'";
$Name = "'" . mysql_real_escape_string($Name) . "'";
$Addr = "'" . mysql_real_escape_string($Addr) . "'";
$PO = "'" . mysql_real_escape_string($PO) . "'";
$sql=("UPDATE $tb1_name SET Employer_Registration_Number ='".$Numb."', Employer_VAT_number = '".$VAT."', Employer_Name = '".$Name."', Employer_Address = '".$Addr."', Employer_Postal_Address = '".$PO."' WHERE Employer_Name = '".$Name."' ");
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Successfully Updated";
mysqli_close($con);
?>
</body>
This here:
$Numb = "'" . mysql_real_escape_string($Numb) . "'";
Firstly, that isn't proper syntax and you're using mysqli_ to connect with, least I sure hope you are.
Those different MySQL APIs do not intermix with each other.
That should read as:
$Numb = mysqli_real_escape_string($con,$Numb);
while doing the same for the rest of your variables, following the same method outlined here.
Footnotes:
Seeing you didn't post what $tb1_name is, doubt that would be causing an issue. But just for the sake of argument, wrap that variable in ticks, just so if your table name changes to something containing a hyphen or a space, or anything that MySQL will complain about.
UPDATE `$tb1_name` SET...
Plus, since you didn't mention which MySQL API you're using to connect with, make sure it is in fact mysqli_ and not mysql_ or PDO.
It doesn't look like it, but I have to be 100% sure.
Your connection should resemble something like this:
$con = mysqli_connect("yourhost","user","pass","your_DB")
or die("Error " . mysqli_error($con));
Again, those different MySQL APIs do not intermix with each other.
Consult (PHP: Choosing an API - Manual): https://php.net/mysqlinfo.api.choosing
"I am very new at MYSQL..."
Seeing you're new to this:
Use mysqli with prepared statements, or PDO with prepared statements.
Additional notes. (as an edit)
I noticed another question you posted earlier:
https://stackoverflow.com/q/30191388/
where you said "Thank you it worked " in the answer given https://stackoverflow.com/a/30191647/
I don't get that.
How could that possibly work where you're using if (!mysqli_query($con,$sql))?
You'll need to show us the way you're connecting with here.
If you truly want to see if your query was successful, use mysqli_affected_rows().
if(mysqli_affected_rows($con)){
echo "Successfully updated.";
}
else{
echo "Not updated.";
}
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Assistance with PHP and MYSQL

I have code here that is supposed to print a html table from my mysql database. When I open the page in my web browser, it is a blank page.
<html>
<body>
<?php
$connection = mysql_connect('localhost', 'admin', 'may122000');
mysql_select_db('contacts');
$query = "SELECT * FROM users";
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysql_close();
?>
</body>
</html>
Remove password
Enable error output
When you use mysql_fetch_array you will get the resulting array with numeric indices.
mysql_fetch_assoc will give you an associative array, like you want.
Note: mysql_* is deprecated.
while($row = mysql_fetch_assoc($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
If you still want to use mysql_fetch_array you'll have to pass a second parameter:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
First of all user mysqli or PDO and mysqli_fetch_assoc() so you have only associative array. Blank page is probably result of a hidden error, that's stored in your error.log on your server - take a look at it and get back to us.
I prefer using PDO or mysqli but anyway , Are u sure Your connection is established ? to check this and check other connections and query :
if (!connection)
die(mysql_error());
try this and feedback me
Improvements - some of which already mentioned in other post but all put together in one form:
<?php
$connection = mysqli_connect('localhost', 'admin', '****', 'contacts');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT first_name, last_name, phone FROM users";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['first_name'] . "</td><td>" . $row['last_name'] . "</td></tr>"; //$row['phone'] the index here is a field name
}
echo "</table>";
mysqli_close($connection);
?>
So, first off the MySQL_* has been upgraded to Mysqli, with some minor reformatting,
The select * has been replaced with selecting only the needed columns.
The closing statement has been correctly set.
Firstly if your connection fails an error catch will output this to the screen. Remove this upon product launch or public launch of the page.
A (Rather rudimentary) error catch has been put in that if the SQL Query is bad that an error is outputted. Again, this should be removed in production but will help you with finding SQL errors.
If No SQL errors return the you have either an empty table in your database, or some sort of PHP error but from the code sample given the most likely error is that your PHP doesn't run MySQL and would only run PDO or MySQLi.
You also said "when I open the page in my browser it is a blank page", if the Source of the page is blank - as in it DOES NOT show
<html>
etc, then this is a sign the PHP execution failed and you have bad PHP, as detailed in your error log file.
The most likely cause of this from the code sample given is, as stated already, your PHP version does not support MySQL.
If your
<table>
Tag appears in your HTML source code then this is a sign that the While clause is not running which means your Datbase table is empty and there is no data to output.
Hope this helps. But first point of call is to upgrade to MySQLi :)

Find coding errors and bad coding practice in php code

I am new to PHP and I have faced an interview some days ago. They gave me a PHP code to find out the errors and bad programming practices. I have pointed out some of the errors and bad practices. But I am not sure about all the bugs in the code. Can you please help me to find out the exact answer, so I can improve my answer in the next interviews.
My suggestions are:
Include an external PHP file based on user request is not a good practice
HTML is mixed with PHP, not using MVC architecture style
Writing connection query in same file
is_authorized() function is not defined
mysql_connect is deprecated, can use mysqli
Here is the code
<?php
function output()
{
// Check authorization
if(is_authorized())
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
}
echo "<ul>";
$conn = mysql_connect( "mysql.foo.org:324", "root", "root" );
mysql_select_db( "conteol", $conn ); // selects a database
$q = " SELECT * FROM main WHERE id > " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
echo "<li>".$row['description']."</li>";
}
echo "</ul><br><ul>";
$q = " SELECT * FROM main WHERE id < " . $_GET["id"]. ";";
$res = mysql_query( $q, $conn);
while( $row = mysql_fetch_assoc( $res ) )
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
echo "<li>".$row['description']."</li>";
// Display the status if it is authorized, othewise display N/A
echo "<li>".$row['description']. "(" .
$authorized ? $row['status'] : "N/A" . ")</li>";
}
echo "</ul>";
}
?>
Some more thoughts:
Using $_GET['id'] directly in an SQL query is not a good idea. You should probably call intval() on it.
Using $row['description'] directly for output is not a good idea. You should probably call htmlspecialchars() on it.
$authorized=true; is set in the code in the while loop without calling is_authorized()
include('/path/to/' . $_REQUEST['module'] . '.php'); is called in the while loop. Should be called outside the loop. Maybe, include_once() is a better idea.
The whole code is executed even if is_authorized() returns false.
I could add some more to that list:
Poor/inconsistent indentation
Inconsistent formatting
Undescriptive variables name
Security vulnerability using $_REQUEST in include
Open to SQL injections using $_GET in SQL queries
Being somebody who has interviewed for new PHP developers myself, it is the security issues that I would have really been looking for.
Formatting/indentation is terrible
$_REQUEST should never be used, always use the method-specific array
No error checking for mysql connection
No SQL injection protection
Do not use include, use include_once
Double MYSQL query for basically the same check: using WHERE id != $id would also work
Authorisation in second loop is always set to true
Displaying "N/A" for something you don't have access to is pointless.

Categories