I'm trying to make a website to access a SQLite database and retrieve info on different people. However, I'm having some problems. Here's my code for my index page.
<?php
$db = new SQLite3('people.db');
$results = $db->query('select FirstName,LastName from People');
?>
<html>
<head>
</head>
<body>
<?php
while ($row = $results->fetchArray()) {
echo '<div class="person"><p class="name"><a href="lookup.php?first=" .
urlencode($row['FirstName']) . '&last=' . urlencode($row['LastName']) . '">' .
$row['FirstName'] . ' ' . $row['LastName'] . '</a></p></div>;
?>
}
?>
</body>
</html>
And the lookup.php code:
<?php
$db = new SQLite3('people.db');
$first = urldecode($_GET['first']);
$last = urldecode($_GET['last']);
$results = $db->query('select * from People where FirstName="' . $first . '" and LastName="' . $last . '"');
$row = $results->fetchArray();
?>
<html>
<head>
</head>
<body>
<div class="person">
Name: <?php echo $row['FirstName'] ?><br/>
Last Name: <?php echo $row['LastName'] ?><br/>
Age: <?php echo $row['Age'] ?><br/>
</div>
</body>
</html>
When I click on a person's name on the index page whose FirstName is "Denzil" and LastName is "Ezras", it works fine. lookup.php displays his FirstName, LastName, and Age. However, I run into problems when a person's first or last name has a space in it. For instance, a person whose FirstName is "James" and LastName is "De Jongh", lookup.php will show no FirstName, LastName, or Age. The URL for this page comes up as:
http://localhost/lookup.php?first=James&last=De+Jongh
I have tried using var_export in PHP to take a look at $first and $last, and they seem in order. When I copy and paste them into sqlite3.exe, it comes up with the proper values. What am I doing wrong?
try this
as i can see from the url, instead of displaying the space as %20 it display it as +
this will convert any spaces to %20 which is acceptable by the url.
$last = str_replace(' ', '%20', $last);
or you can simply use
rawurlencode($lastName);
Related
I am trying to insert values to a database with a foreach loop. It all works fine but the last element of the array gets inserted twice.
I understand that a reference of a $photo and the last array element remain even after the foreach loop. I am trying to destroy it by using unset($photo) but that does not seem to work, I still get double insert inside my database of the last element.
Can someone explain this to me?
// value of $photos
<?php
$stmt = $conn->prepare(
"SELECT p.*, pt.propertyType
FROM tbl_property p
JOIN tbl_propertyType pt USING (PropertyType_Id)
ORDER BY Price;"
);
$stmt->execute();
?>
<form id = "prop-form" action="../scripts/photo-property.php" method = "POST" enctype="multipart/form-data">
<select name="property">
<?php while($row = $stmt->fetch()){ ?>
<option value="<?php echo $row['Property_Id'];?>"><?php echo $row['propertyType'] . ', ' . 'Price: ' . $row['Price'] . ', ' . $row['BuildingNameStreetNo']
. ', ' . $row['Street'] . ', ' . $row['Town'] . ', ' . $row['Condition']
. ', ' . $row['RoomNo'] . ' Rooms'; ?></option>
<?php } ?>
</select>
<?php $sql = $conn->prepare("SELECT * FROM tbl_Photo");
$sql->execute();
while($row = $sql->fetch()){
echo '<img class="propimg" src=../photos/'. $row['Photo'] . '><br/>';
echo '<input type="checkbox" name="photos[]" value="'. $row['Photo_Id'] . '">';
}
?>
</form>
-------------
// DIFFERENT FILE
// assign the array values from the form
$photos = $_POST['photos'];
// for each photo, bind the param and execute the query
$sql = $conn->prepare("INSERT INTO tbl_propertyphoto (Property_Id, Photo_Id) VALUES (:prop, :photo)");
foreach($photos as $photo) {
$sql->bindParam(':prop', $_POST['property']);
$sql->bindValue(':photo', $photo);
$sql->execute();
}
unset($photo);
Check if your tbl_Photo table hasn't multiple of the same rows.
Try to make the columns Property_Id and Photo_Id UNIQUE together.
In that way you cannot have the same combination twice.
ALTER TABLE tbl_propertyphoto ADD CONSTRAINT UQ_Property_Photo UNIQUE(Property_Id, Photo_Id)
I have two tables. They are connected via a one (userinfo) to many (achievements) foreign key relationship. What I am attempting to do below is echo all the rows which have the given $usrid. This could be more than one.
Unfortunately, It only echos content one of the rows. How can I change it to echo all the rows where a a certain userid is present?
<!DOCTYPE HTML>
<head>
<?php $usrid = $_GET['usrid'];
$connection = #mysqli_connect("localhost","root","","Rain")
OR die('Could not connect' .
mysqli_connect_error());
$query = "SELECT usrid, username, oldname, languages, joindate, art, hunting, frontwebdev, backwebdev, writing, programming, se, smm, pentesting, timezone, availability, reliability, profilePicture FROM userinfo WHERE usrid='" . $usrid . "';";
$response = #mysqli_query($connection,$query);
$row = #mysqli_fetch_array($response);
$username = $row['username'];
$achvquery = "SELECT achieveid, usrid, achievementname, achievementdescr, timestamp FROM achievements WHERE usrid=" . $usrid . ";";
$achvresponse = #mysqli_query($connection,$achvquery);
$achvrow = #mysqli_fetch_array($achvresponse);
$achvtitle = $achvrow['achievementname'];
$achvdescr = $achvrow['achievementdescr'];
?>
<title>
All Achievements
</title>
</head>
<body>
<span> <?php echo "<span> " . $username . "s OD Achievement History "; ?> </span>
<span id="newAchvLink"> <?php echo "<a id='addNewLink' href='addachievement.php?usrid=" . $usrid . "'> Add new</a>"; ?></span>
<br /> <?php echo "<h2> Achv: </h2> <h3 class='achvtitle'>" . $achvtitle . "</h3>"; echo $achvdescr;?><br /><br />
</body>
</html>
You can use while loop to print all row
$query = "SELECT usrid, username, oldname, languages, joindate, art, hunting, frontwebdev, backwebdev, writing, programming, se, smm, pentesting, timezone,
availability, reliability, profilePicture FROM userinfo WHERE usrid='" . $usrid . "';";
$response = #mysqli_query($connection,$query);
while ($row = #mysqli_fetch_array($response))
{
echo $row['username'];
}
Where you have the PHP echo statement you can replace it with something like...
while($row = $result->fetch_assoc($response)) {
echo "<span> " . $username . "s Op Achievement History ";
You should look at JOIN to simplify all of this for you.
https://www.w3schools.com/sql/sql_join.asp
This is a pretty good/easy to understand usage of PHP Loops.
https://www.tutorialspoint.com/php/php_loop_types.htm
first table query
while loop
{
$userid=first_table_data['user_id'];
2nd table query where userid=$userid
while loop
{
}
all value save in array
}
print value
I am using the toggle visibility function in order to display and hide divs in one page.
Clicking on this link News makes a div visible where all the current news are displayed from the database using this code.
<?php
include"scripts/connect_to_mysql.php";
mysql_query("SET NAMES 'utf8'");
mysql_query("SET CHARACTER SET 'utf8'");
$news="";
$sql=mysql_query("SELECT *
FROM `news`
ORDER BY date DESC");
$newsCount=mysql_num_rows($sql);
if ($newsCount>0) {
while($row=mysql_fetch_array($sql)){
$id=$row["id"];
$title=$row["title"];
$text=$row["text"];
$date=$row["date"];
$news.=' <table width="800" border="0">
<tr>
<td style="width:150px;">' . $date . '</td>
<td style="width:600px; overflow:hidden;"><a href="#?id=' . $id . '" onclick="toggle_visibility(\'news_det\');" style="color:#b19057;" >' . $title . '</a></td>
<td style="width:50px">...more</td>
</tr>
</table>
';
}
}else {
$news="No news available yet";
}
?>
The problem is that by clicking on the results, the div where the detailed news should appear, appears, but I can't get the data from the database.
I use this code the get the id sent from the previous links.
if(isset($_GET['id'])){
$newsid= preg_replace('#[^0-9]#i','',$_GET['id']);
$sql = mysql_query("SELECT * FROM news WHERE id='$newsid' LIMIT 1");
$newsCount1 = mysql_num_rows($sql);
if ($newsCount1 > 0) {
while($row = mysql_fetch_array($sql)){
$dettitle = $row["title"];
$dettext = $row["text"];
$detdate = $row["date"];
}
}
else {
echo "No news with that id";
exit();
}
}
What am I doing wrong?
How to get the variable with PHP?
Let's say you have a PHP page named people.php. Now you can call this page using the following URL:
people.php?name=Joe
With PHP, you will be able to get the value of the variable 'name' like this:
$_GET["name"]
So, you use documentation $_GET to find the value of a named variable. Let's try it in an example:
<html>
<head>
<title>Query string</title>
</head>
<body>
<?php
// The value of the variable name is found
echo "<h1>Hello " . $_GET["name"] . "</h1>";
?>
</body>
</html>
May be its because you are using '#' in link
Change href="#?id=' . $id . '" to href="?id=' . $id . '"
If you are not refreshing the page then you should use ajax for this.
I'm pretty new to php, and for that matter server scripting in general (so go easy on me)
But regardless of that I managed to create this, the first half of a comment system:
<html>
<body>
<form name="Comment" action="InsertComment.php" method="POST">
Name: <input type="text" name="name" /><br>
Comment: <br><textarea style="height: 100px; width: 600px;" name="comment"></textarea><br>
<input id="Special_ID" name="id" value="<?php $unixtime = time(); echo $unixtime; ?>">
<!--^Gathers a unique id^-->
<input type="submit" />
</form>
</body>
</html>
Once submitted -->
<?php
$con = mysql_connect("Blaa", "Blaa", "Blaa");
if(!$con) {
die('Could not connect ' . mysql_error());
}
sql_select_db("Comments", $con);
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('$_POST[name]', '$_POST[comment]', '$_POST[id]')";
?>
This is exactly what I wanted, a user puts in their name, a comment, and a unique post id (time stamp) is generated, then it is all sent to mysql.
But now I'm dumb found as to how I can post this to another page..
I assumed something like:
if(ID == [the id of that post]) {
//$_GET the mysql stuff
//Post inside a specially made div or something
}
Along the lines of that, but I have no clue how to put that into practise :/
Any ideas?
Oh and Please don't suggest an echo type post, I've done that and it's not at all what I want.
**Also this is just the basic code, I don't need suggestions on how to touch it up just yet, also errors in this is only due to my sleep deprivation, the code does work.
As #Marc B has said, you'll first want to fix your SQL injection holes using mysql_real_escape_string. Change your insert statement to
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('" . mysql_real_escape_string($_POST['name']) . "', '" . mysql_real_escape_string($_POST['comment']) . "', '" . mysql_real_escape_string($_POST['id']) . "')";
To display your comment, try this
$sql = "SELECT Name, Comment, ID
FROM Posts
WHERE ID = '" . mysql_real_escape_string($_GET['PostID']) . "'";
$query = mysql_query($sql);
echo "<div id=\"comments_container\">";
while ($row = mysql_fetch_assoc($query))
{
echo "<div class=\"comment\">";
echo "<div class=\"name\">" . $row['Name'] . "</div>";
echo "<div class=\"comment_body\">" . $row['Comment'] . "</div>";
echo "</div>"
}
echo "</div>";
Then CSS style your DIVs using IDs and classes.
Just an example using mysql_fetch_object
Please sanitize your $_GET data before inserting to MySQL, this is a huge injection security flaw.
$sql = "SELECT * FROM Posts WHERE id={$id}"
$result = mysql_query($sql);
$obj = mysql_fetch_object($result)
if(is_object($obj))
{
echo "Welcome " . $obj->Name;
}
A full length example is given here:
http://manzur-ashraf.com/code/auto_commenting_system/Automatic_Commenting_System_and_Email_notification_using_PHP_and_MYSQL.htm
In addition to using a MYSQL database to store the comments, you can also post email to the admin about new comments.
I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop