sql query not pulling records - php

For some reason SQL does not pull required info from needed table. Which is odd because I use exactly same code for pulling list of Folders associated with user id from SQL and that works like it should. So a URL query would look something like this ?o=folder&fid=0ec741fa-e708-4314-83c4-c05966a56110, fid is the folder ID and the query below should pull any files assosiated with such folder ID but instead there is nothing being returned, not even an error message/code.
Is there a problem with the syntax? Or what is the cause of the problem?
CORRECTION I USED WRONG CODE AS I HAVE BUNCH OF TABS OPEN IN NOTEPAD++
Here is the actuall code written in SQL PDO
require ("sql/pdo.php");
// Lets get user's folder information
$query = " SELECT * FROM files WHERE fid = ".$_REQUEST['fid']." ";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
<table width="100%">
<?php foreach($rows as $row): ?>
<tr onclick="window.location = 'file.php?fid=<?php echo htmlentities($row['id'], ENT_QUOTES, 'UTF-8')."'">
<td style="width:4%;"><img src="ast/images/fs-directory.png" /></td>
<td style="width:86%;text-align:left;"><?php echo htmlentities($row['name'], ENT_QUOTES, 'UTF-8'); ?></td>
<td style="width:10%;text-align:center;"><?php echo htmlentities($row['privacy'], ENT_QUOTES, 'UTF-8'); ?></td>
</tr>
<?php endforeach; ?>
</table>

In your query u are using $_GET['f']
but in your url u are passing fid
code might work when u replace $_GET['f'] with $_GET['fid']
<?php
$sql = mysql_query("SELECT * FROM `fs_files` WHERE fid = '".$_GET['fid']."'") or die(mysql_error());
while($row = mysql_fetch_array( $sql )) {
if (in_array($row['file_type'], array('jpeg', 'jpg', 'png', 'gif'))) {
$img = "obj.php?id=".base64_encode($row['file_path'])."&mode;thumb";
} else {
$img = "assets/filesystem/file_extension_".$row['file_type'].".png";
}
$type = $row['file_type'];
$file_name = substr($row['file_name'], 0, 50);
$file_path = "view/".$_GET['fid']."/".$row['id']."/".$row['file_name'];
echo '<a href="?p=view&f='.$row['id'].'&q='.$file_path.'"><img src="'.$img.'" />'.$file_name.'
<span style="float:right;">'.$type.'</span></a>';
}
?>

The code is basically correct, you should use PHPmyadmin or other tools to check the content of the database to see what it's retrieving.
Be careful because putting values inside the SQL query directly from the GET parameters is dangerous, in your case someone (or a n automatic script) may inject an arbitrary SQL code using the 'f' GET parameter. You should escape it removing all characters not strictly used by your case (for example, keep only letters and numbers).
The same applies to the same parameters inside $file_path, it could be used to insert an arbitrary image from anywhere in internet, or even a script or an arbitrary HTML code.
You should describe your table schema to understand what's happening here.

Related

Carry over specific data from mysql query result when user selects data

This is my first ever question on stackover flow so hope i explain it well. I am fairly new to php/js/html and i have run into a problem. I query my database using a session variable and it returns all the results that are associated with the logged in user.
Below is the php code i used to get the results.
<?php
session_start();
include('conn.php');
if(!isset($_SESSION['40219357_user'])){
header('Location:index.php');
}
$username = $_SESSION['40219357_user'];
$userid = $_SESSION['40219357_id'];
$read = "SELECT * FROM medi_users WHERE dr_id = '$userid'";
$result = $conn ->query($read);
?>
The result of this query is displayed in a table on my website. When the logged in user of the website clicks on a person's record it should show all the information relating to that specific person.
Since asking my original question i have found a simple solution to my problem by passing the user id as a hidden value in a button. The code for this is below.
<?php
while($row = $result ->fetch_assoc()){
$rowid = $row['id'];
$firstname = $row['firstname'];
$surname = $row ['surname'];
$dob = $row['dob'];
$address = $row['address'];
$town = $row['town'];
$postcode = $row['postcode'];
echo"
<tbody>
<tr>
<td>$firstname</td>
<td>$surname </td>
<td>$dob</td>
<td>$address</td>
<td>$town</td>
<td>$postcode</td>
<td><a class = 'btn btn-danger'
href `='patientsmedication.php?editid=$rowid'>View</a></td>`
</tr>
";
}
?>
</tbody>
</table>
</div>
</div>
I fully understand that this is not a very secure way of doing this and i would be open to suggestions as to how to do this correctly as i am keen to learn.
<?php
session_start();
//I think you are already using PDO/Mysqli prepared statements
//in this file since you call $conn->query below
include('conn.php');
if(!isset($_SESSION['40219357_user'])){
header('Location:index.php');
}
//
$username = $_SESSION['40219357_user'];
$userid = $_SESSION['40219357_id'];
//so to make this secure use place markers and bind your params
$read = "SELECT * FROM medi_users WHERE dr_id = '$userid'";
//becomes:
$read = "SELECT * FROM medi_users WHERE dr_id = :userId";
$q = $conn->prepare($read);
$q->bindParam(":userId",$userId,PDO::PARAM_INT);
$q->execute();
//now you can fetch your result set and store it in a variable
$results = $q->fetchAll();
?>
then you can loop through the results with a foreach
echo "<table>
<tr>
<th>Heading 1</th><th.....
</tr>";
foreach($results as $row) {
$rowid = $row['id'];
//I'm not sure if this is the right id,
//you would need to confirm, I would think you want to have a user id, but obviously don't know the structure
//of your database - if this is the user (patient?)
//id then it's fine
$firstname = $row['firstname'];
$surname = $row ['surname'];
$dob = $row['dob'];
$address = $row['address'];
$town = $row['town'];
$postcode = $row['postcode'];
echo "<tr>
<td>$firstname</td>
<td>$surname </td>
<td>$dob</td>
<td>$address</td>
<td>$town</td>
<td>$postcode</td>
<td><a class='btn btn-danger'
href='patientsmedication.php?patientId=$rowid'>View</a></td>//or whatever the relevant id is
</tr>";
}
echo "</table">;
I'm sure there are mixed feelings about passing an id in the url - personally I am not a big fan but we do it where I work for read only situations, if you have enough other checks in place then the id on it's own isn't really very useful to anyone.
Now in patientsmedication.php you can get the patients id using $_GET['patientId']
<?php
session_start();
include('conn.php');
if(!can_view_patient_details()) {
header('Location:error_page.php');
exit();
} else {
$patientId = isset($_GET['patientId'])??0;
//if you aren't using php7 you won't have the null coalescing operator so use a ternary style like $var = cond ? A : B
//now do your query
$q = "SELECT * FROM yourtable WHERE patientId = :patientId";
$q = $conn->prepare($q);
$q->bindParam(":patientId",$patientId,PDO::PARAM_INT);
$q->execute();
//now you can fetch your result set and store it in a variable
$results = $q->fetchAll();
}
function can_view_patient_details() {
//this should return true or false
//you would need to design your own permissions checks,
//given the nature of your project I would think you would
//do a database call to confirm the user has the right access
//to the patient, but you may just check that the correct
//sessions are set, you'd have to decide what is most appropriate
}
?>
Then with your result you can create the page as you see fit - if you are going to use this page to update details I would suggest a form because you can use the $_POST method which doesn't show the information in the url - then I would suggest it goes through a controller to do all the correct checks for permissions, data types etc.
If you haven't got into MVC patterns (which is likely if you are just starting out) then at least direct your form to a separate script, and then return to this page with some feedback - either by a flag in the url or by setting a session message and echoing it out.
A couple of things worth noting are that I assume you are using PDO not Mysqli prepared statements, they are both fine but the syntax is slightly different and my answer only uses PDO also in PDO you no longer need to use semi colons on your place markers (:userId == userId) but I personally prefer it for readability when writing sql. Also your session names look like they have the user id in the name ( it might be an internal code though that means something though), but if it is the id it's not very scalable to set it up this way - it's more simple to just have a session called 'user' and give it the value of the id - otherwise how would you know the name of the session without looking up the user, which would defeat the object.
Hopefully this will point you in the right direction, I recommend reading up on PDO and MVC patterns

error to upload to images with php

I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}

My PHP-Code won't run no matter what I do

Good day people,
some days ago, I started learning php and now I'm at the point where I intend to teach myself database queries with mysql.
My current code, however, won't process anything.
It's supposed to take text input from the index.html, pass it to a.php and have the a.php look for the (name /) input string in a database (phone book), then output the matching row(s) in a table.
It consists of two parts; the index.html which is just the following:
<form action="a.php">
<input type="text" name="q">
<input type="submit">
</form>
and the a.php which is supposed to process the inputted data:
<?php
echo $_GET['q'];
$such = $_GET['q'];
$mysqliu = new mysqli("HOST", "User", "Password", "Database");
$sql="Select * from LIST where name like '%$such%'";
$result = mysqli_query($mysqliu,$sql);
if($result = $mysqliu->query($sql)) {
echo "<table><tr><th>Kennummer</th><th>Name</th><th>Strasse</th><th>PLZ</th><th>Telefon</th></tr>";
while($row = $result->fetch_array() ) {
echo "<tr>";
echo "<td>" , "$row[0]" , "</td>";
echo "<td>" , "$row[1]" , "</td>";
echo "<td>" , "$row[2]" , "</td>";
echo "<td>" , "$row[3]" , "</td>";
echo "<td>" , "$row[4]" , "</td>";
echo "</tr>";
}
}
$result->close();
echo "</table>";
else {
echo"Nope"
}
$mysqliu->close();
?>
I tried outcommenting as much as possible to see where it breaks and it seems that as soon as I want to do something to "q" (the query from index.html), it breaks.
The above code doesn't contain the SQL connection data but that's present in my code.
The issue is not related to the PHP server or anything server-side so I'm sure I'm doing something wrong.
I can echo the variable q in a.php so it's passed over but whatever I do after that, nothing happens and I get a blank page.
Can you experts help me please?
Solved: It was the ; missing right at the end.
Thanks to everyone for their input.
Regards~
Try to add a method in the form tag like GET or POST. Set a default value for the q field. Also set a name for the type submit and dump the whole $_GET or $_POST array in the php file.
I won't give you the exact answer, I'll let you figure it out...
use error_reporting
Check your IF-ELSE statement, does it look correct??
Note:
You don't have a method attribute in your <form>
What if a user just typed-in their browser, a.php? You should be validating the page so user can't just access this page
Is your table really LIST? Be case sensitive about it.
Your query is still prone to SQL injections. You should be using mysqli_real_escape_string() extension of PHP, or better use mysqli_* prepared statement.
Your form should look like this:
<form action="a.php" method="GET">
And sanitize the values of your passed on data:
$such = mysqli_real_escape_string($mysqliu,$_GET["q"]);
If you are curious with prepared statement, you can try this:
$such = "%".$_GET["q"]."%";
$mysqliu = new mysqli("HOST", "User", "Password", "Database"); /* REPLACE NECESSARY DATA */
if($stmt = $mysqliu->prepare("SELECT kennummer,name,strasse,plz,telefon FROM LIST WHERE name LIKE ?")){ /* REPLACE NECESSARY COLUMN NAME */
$stmt->bind_param("s",$such); /* BIND PARAMETER TO THE QUERY */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($kennummer,$name,$strasse,$plz,$telefon); /* BIND THE RESULT TO VARIABLE */
?>
<table>
<tr>
<th>Kennummer</th>
<th>Name</th>
<th>Strasse</th>
<th>PLZ</th>
<th>Telefon</th>
</tr>
<?php
while($stmt->fetch()){ /* LOOP THE RESULT */
?>
<tr>
<td><?php echo $kennummer; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $strasse; ?></td>
<td><?php echo $plz; ?></td>
<td><?php echo $telefon; ?></td>
</tr>
<?php
}
?>
</table>
<?php
$stmt->close();
}
Solved: It was the ; missing right at the end. Thanks to everyone for their input.
First, you need to enable error reporting in the page using error_reporting(-1);. As you are getting error but that is not getting display because error reporting is OFF.
Second, your code welcomes to SQL injections So It is better to learn first that how you can avoid SQL injections after that approach for queries in database.
Third, You need to check MySQLi extension is installed or not on your PHP. Use var_dump(function_exists('mysqli_connect')); and then check the output.
Fourth, $mysqli->fetch_array(); returns weird results sometimes that is because of old PHP version so that can be a reason of error, please check once with that.
Fifth, I believe there is an error with your if else statement. else statement should start after } of if statement .
I can edit my answer once you please show the exact error in your question from error log meanwhile you can check with these.

SQL database not inserting data?

I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.

Issue getting variable from link

I have this code which permits me to pass a variable to another page, but the problem is i cannot seem to get that variable using the link. We have tried before, this same method and has worked.. could you please check it?
Thanks..
The link:
$sql="SELECT * FROM pianificazione";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['job'] ?>
<?php echo '</br><br />'; }
?>
The page after the link:
include('menu.php');
$id=$_GET['job_id'];
$sql="SELECT * FROM attivita WHERE job_id='$id'";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
?>
<?php echo $row['attivita_da_promuovere'] ?>-<?php echo $row['attivita_tip_merc'] ?>-<?php echo $row['attivita_da_svolgere'] ?>-<?php echo $row['attivita_tip_personale'] ?>
You should be using:
$id = $_GET['id'];
You're also open to SQL injections... Either parse it as an INT:
$id = (int) $_GET['id'];
... or use prepared statements with PDO (instead of the default mysql functions that you're using, which are no longer recommended).
You're passing it as:
lista_attivita.php?&id=<?php echo $row['job_id'] ; ?>
And then looking for it as:
$id=$_GET['job_id'];
You should use:
$id=$_GET['id'];
In the URL that you're passing to the "page after link" you're setting "?id=xxx" as the parameter however in your script, your looking for "job_id".
Change the parameter to ?job_id= in your first script.
Two things.
1) FUNCTIONALITY
$id=$_GET['job_id'];
should be
$id=$_GET['id'];
since your link passes the variable id, not job_id:
lista_attivita.php?&**id**=<?php echo $row['job_id']
2) SECURITY
Never, NEVER insert user-input data directly into a SQL query. You are asking for headaches or worse. The $id on your receiving page should be validated and escaped prior to doing any lookup. If you expect a number, do something like this on the receiving page:
if (!is_numeric($_GET['id']))
{
// throw error
}
It's not a bad idea to query your DB for valid codes, put those in an array, then check that array to see if the passed value is found. This prevents user entered data from reaching your DB.
Something like this:
$q = "SELECT DISTINCT(id) FROM my_table WHERE display=1 ORDER BY id ASC";
$res = mysqli_query($dbx,$q);
while (list($_id) = mysqli_fetch_array)
{
$arr_valid_id[] = $_id;
}
Then,
if (in_array($_GET[id],$arr_valid_id[])
{
// do stuff
} else {
// throw error
}

Categories