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.
Related
This question already has answers here:
Escape double quotes with variable inside HTML echo [duplicate]
(3 answers)
Closed 1 year ago.
First want to start off by saying that I am still a beginner developer but have gotten a long way in a short time and I am somewhat stumped. And yes I know my code might not be pretty in layout, but still learning, at least things are working.
I am creating something that is like a client portal for shows. A client signs up to do a show from an intake form. When they submit the form, it goes to Monday.com, creates a folder and sub folder in dropbox and then inserts everything into my Mysql database. I also then have another page (Assets) where they can upload files based on the show. Now if they have signed up for multiple shows, at the top of this page I have a dropdown box that grabs all the shows that is assigned to their used id. When they click on the show that they want to add files to and then click the "Choose Show For Asset Upload" button it goes back to the database to retrieve the dropbox path and the file request url and puts it into the code where those variables are assigned. So, everything is working great except when it comes to a show that has a single quote (apostrophe). I noticed this when I added a test show and everything went bonkers. I was able to figure everything out when it comes to making it correct in the code for Monday and Dropbox and even INSERTing it into the database. In the database column it has "Michael's" instead of "Michael\'s", so it's exactly how it should be in there. In the dropdown it actually shows "Michael's" but yet when I do an echo after clicking the button it shows "Michael" So that single quote is definitely the issue and this is where I don't know how to fix it, after much searching through the net.
In the dropdown it lists (Show Test, Did I Really Do It!!, Dudley, The Amazing MA, Lets See If This Works, Michael's).
Code is:
<div class="topdiv">
<h2 style="text-align: center;">Assets Upload</h2><br>
</div>
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM intake WHERE userid = ?;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $userid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
}
?>
<form class="formcenter" action="assets.php" method="post">
<select name="show" id="show">
<?php
while ($rows = mysqli_fetch_assoc($result)) {
$show = $rows['showtitle'];
echo "<option value='$show'>$show</option>";
}
?>
</select>
<input type="submit" name="chooseShow" value="Choose Show For Asset Upload"><br><br>
</form>
<?php
if(isset($_POST["chooseShow"])) {
$showTitle = $_POST["show"]; //WHEN I DO AN ECHO OF THIS IT SHOWS "MICHAEL" NOT "MICHAEL'S"
$sql = "SELECT * FROM intake WHERE userid = ? and showtitle = ? ;";
$stmt = mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt, $sql)){
echo "There was an internal error!";
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $userid, $showTitle);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$rows = mysqli_fetch_assoc($result);
$path = $rows['dbxPath'];
$requestURL = $rows['requestURL'];
echo $show; //THERE JUST TO SEE WHAT IT WAS OUTPUTTING
echo $showTitle; //THERE JUST TO SEE WHAT WAS OUTPUTTING
}
}
?>
When I do the two echos at the end of the code $show = "Michael's" and $showTitle = "Michael". So I do know that the correct way is coming through but just can't grab it to put in the last $sql variable to use as the $showTitle Granted, I am assuming the $show is showing "Michael's" because it's the last show in the loop. BUT when I tested $show instead of $showTitle in the mysqli_stmt_bind_param statement it actually worked, so I know it's possible. Just need to know how to get the full "Michael's" into my $showTitle variable.
Thank you for taking the time to look through this longwinded (trying to give you as much info as possible) question and appreciate any help and advice.
-Michael
Your problem is here:
echo "<option value='$show'>$show</option>";
The single quotes in the variable $show are interfering with the single quotes wrapping the value.
Change it to this:
echo '<option value="'.$show.'">'.$show."</option>";
This explicitly concatenates the parts of the string rather than interpolating it. It gives better control over what quotes are used and where.
I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
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.
I'm having a little problem with passing a parameter for a query to another page.
I want to make the name of the restaurant a link that would pass the name of the product to process a query on the next page.
echo "<p class='p2'><a class='link' href='restaurant.php?name=". $row['name'] ."'><strong>". $row['name'] ."</strong></a>
on the restaurant page
<?php
require ("db.php");
$name = $_GET['name'];
$query = "SELECT * FROM restaurant WHERE name =\"$name\"";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
?>
but nothing is displayed.
Any idea what I'm doing wrong?
First, a note: you should pass an ID rather than the name, since certain characters aren't great in URLs.
Second, try using urlencode() on the name.
echo "<p class='p2'><a class='link' href='restaurant.php?name=". urlencode($row['name']) ."'><strong>". $row['name'] ."</strong></a>
Of course it won't display anything, because you don't have any print functions (echo, print, var_dump, ...) in your file.
Anyways, you probably thought that your query doesn't work. If so, try to echo your $row['name']. If everything's OK, check if your variable is set, but it probably isn't because you get null.
To fix that issue, use isset() or empty().
Example:
if(!empty($_GET['name'])) $name = $_GET['name'];
else die('Variable name is empty');
Try also to add ini_set('display_errors', true) to the top of your pages to see if there's any errors.
Note that your code is very insecure and vulnerable. Use mysql_real_escape_string() before executing queries.
Example:
$name = mysql_real_escape_string($_GET['name']);