Insert into mysql using div codes and php - php

the below to functions contain the code to insert into the sql database but sadly the db is still unable to load it to the database.
if (isset($_POST['register'])){
if(registerNewUser($_POST['inv_amount_expected'],$_POST['uname'],$_POST['passwo rd'],$_POST['email'])){
echo "You can now log-in to your account.
<a href='./index.php'>Click here to login.</a>
";
}else {
echo "Registration failed! Please try again.";
show_registration_form();
}
} else {
// has not pressed the register button
show_registration_form();
}
function registerNewUser($inv_amount_expected,$uname,$password,$email)
{
$sql = sprintf("insert into borrow (inv_amount_expected,uname,password,email) value ('&inv_amount_expected','&uname','&password','&email')",
mysql_real_escape_string($username), mysql_real_escape_string(sha1($password . $seed))
, mysql_real_escape_string($email), mysql_real_escape_string($code));
if (mysql_query($sql))
{
$id = mysql_insert_id();
return true;
}
else
{
return false;
}
return false;
}
could you help me out in where i am going wrong since im unable to understand.
i'm still an amature in php so please help me out.

I am putting my ideas together and at the moment i have the following:
-a mysql database with 2 tables.
-the first table "downloads" contains 3 rows, each with a unique id that and each represent the type of file being downloaded. e.g. application or theme.
-the second table contains the information about each download, these fields are the models supported by the download, the title, a picture, a brief description and a download link. each download has a unique id.
Now what i am trying to do is insert the data into a set of divs, these divs are as follows:
<div class="dlcontainer">
<div class="dlitem">
<div class="dltitle"><php $row['title'] ?></div>";
<div class="dlimage"><php $row['image'] ?></div>";
<div class="dldescription"><php $row['description'] ?></div>";
<div class="dllink"><php $row['downlink'] ?></div>";
</div>
</div>
As you can see i have been trying to populate the divs with information called from the database and that was my first attempt.
I didn't feel like i was going about this with the right approach, so i ended up with this, which also does not seem to work:
<?php
$con = mysql_connect("test","test","test");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$result = mysql_query("SELECT * FROM `content` WHERE pid = '2' AND models = 'all' OR models = $chosen");
while($row = mysql_fetch_array($result))
{
echo "<div class=\\"dlcontainer\\">";
echo "<div class=\\"dlitem\\">";
echo "<div class=\\"dltitle\\">$row['title']</div>";
echo "<div class=\\"dlimage\\">$row['image']</div>";
echo "<div class=\\"dldescription\\">$row['description']</div>";
echo "<div class=\\"dllink\\">$row['downlink']</div>";
echo "</div>";
echo "</div>";
}
mysql_close($con);
?>
Once i get this initial download working, i can then set up a loop that will display all the contents that match belong to a specific "pid" and either match a "models" value of "all" or one that has been selected by the user.

Related

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

PHP + HTML table: Fire appropriate MySql query from each cell of the table

The title is not most suitable, but this is the best I could think of. Feel free to suggest EDIT.
Summary:
I have come from Android development where I have used RecyclerView to show a grid of various items from the database. There I could use the onClickListener()and Position to get which RecyclerView item (first,second,third..) is clicked by user and can proceed with actions.
Set up:
I am new to web development and by far I have managed to create an HTML table and I am firing appropriate query to get items from the database. I am then showing these data from database in each table cell. The data consists of image link (from a folder in same directory) and other text data about that image. My table looks something like this. Click here
Problem:
I want to add an options like Accept in each cell of the table such that when user clicks on that, a query fires to set the Boolean isAccepted for that item in DB as true. I can manage the query part but I am facing problem how to set this up in my php script.
What do I ecpect?
That's absolutely OK if I dont get the ready made code. I want to be guided as what technology to be used and if possible a link to the guiding tutorial. I hope it can be done usng PHP and HTML only.
My php script:
<table id="customers">
<?php
$MAX_COLS = 5;
$query = "select * FROM `complaints`";
$result = mysqli_query($conn,$query);
$i = 0;
while($row = mysqli_fetch_row($result)){
if($i % $MAX_COLS == 0){
echo "<tr>";
}
echo "<td>";
echo "<img src='SCB2/Images/temp2.jpg' alt='Sample image' style='width:200px;height:200px;' >";
echo "<br>"."Image ID: ".$row[0];
echo "<br>"."Latitude: ".$row[2];
echo "<br>"."Longitude: ".$row[3];
echo "<br>"."Zip: ".$row[4];
echo "<br>"."Done by: ".$row[8];
echo "<td>";
$i++;
if($i % $MAX_COLS == 0){
echo "</tr>";
}
}
?>
</table>
You can add the link to the HTML that is outputted:
echo "<td>";
// ...
echo "<br><a href='/some/path/to/accept.php?imageid={$row[0]}'>Accept</a>";
echo "<td>";
And then in the accept file you can deal with it:
// /some/path/to/accept.php
// Get the image id from the query string
$imageid = filter_input(INPUT_GET, 'imageid', FILTER_VALIDATE_INT);
try {
// Create a database connection
$db = new PDO(
'mysql:dbname=databaseName;host=localhost',
'username', 'pa55w0rd',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
// Create a prepared statement and bind the image id to it
$stmt = $db->prepare('UPDATE complaints SET isAccepted = 1 WHERE Id = :id');
$stmt->bindValue(':id', $imageid, PDO::PARAM_INT);
// Execute the statement
if ($stmt->execute()) {
die('SUCCESS!');
} else {
die($stmt->error);
}
}
catch (\PDOException $e) {
die('PDO Exception: ' . $e->getMessage());
}
You should obviously do some checks that the user is allowed to accept the image.

HTML link with a php action

I am creating a website that stores information of homes like address, city etc. I got the upload to database part done and I got the search the database and display the information done.
But now my plan with that is you get the search results and from there your suppose to get the option to view the full profile of that home via link. Displaying the full profile with the information gathered from the database is already done through a separate php file. Now when I link the php file it will only display the last column in the database. How can I link it so when I click on "view full profile" it will connect to the correct data/profile that corresponds to the different address or price. Or if i cant use an html link what can I use? Is that impossible?
here is the code that displays the search results I have successfully been able to search the database and display it
<?php
if($sql->num_rows){
while ($row = $sql->fetch_array(MYSQLI_ASSOC)){
echo '<div id="listing">
<div id="propertyImage">
<img src="images/'.$row['imageName1'].'" width="200" height="150" alt=""/>
</div>
<div id="basicInfo">
<h2>$'.$row['Price'].'</h2>
<p style="font-size: 18px;"># '.$row['StreetAddress'].', '.$row['City'].', BC</p>
<p>'.$row['NumBed'].' Bedrooms | '.$row['NumBath'].' Bathrooms | '.$row['Property'].'</p>
<br>
<p>View Full Details | Get Directions
</div>
</div>';
height="150" alt=""/>';
}
}
else
{
echo '<h2>0 Search Results</h2>';
}
?>
Here is the php to display the information outputtest.php
<?php
mysql_connect("localhost","root","31588patrick");
#mysql_select_db("test") or die( "Unable to select database");
$query="SELECT * FROM propertyinfo";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$varStreetAddress=mysql_result($result,$i,"StreetAddress");
$varCity=mysql_result($result,$i,"City");
$varProperty=mysql_result($result,$i,"Property");
$varNumBed=mysql_result($result,$i,"NumBed");
$varNumBath=mysql_result($result,$i,"NumBath");
$varPrice=mysql_result($result,$i,"Price");
$varEmail=mysql_result($result,$i,"Email");
$varPhone=mysql_result($result,$i,"Phone");
$varUtilities=mysql_result($result,$i,"utilities");
$varTermLease=mysql_result($result,$i,"TermLease");
$varNotes=mysql_result($result,$i,"Notes");
$image1=mysql_result($result,$i,"imageName1");
$image2=mysql_result($result,$i,"imageName2");
$image3=mysql_result($result,$i,"imageName3");
$image4=mysql_result($result,$i,"imageName4");
$i++;
}
?> html code will go after this
Thanks
edit its working
<?php
////////////using mysqli to connect with database
$mysqli = new mysqli("localhost","root","31588patrick", "test");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
///////////set variables
$record_id = $_GET['record_id'];
$sql = $mysqli->query("select * from propertyinfo where StreetAddress like '%$record_id%'");
if($sql === FALSE) {
die(mysql_error()); // TODO: better error handling
}
if($sql->num_rows){
while ($row = $sql->fetch_array(MYSQLI_ASSOC)){
$varStreetAddress=$row['StreetAddress'];
$varCity=$row['City'];
$varProperty=$row['Property'];
$varNumBed=$row['NumBed'];
$varNumBath=$row['NumBath'];
$varPrice=$row['Price'];
$varEmail=$row['Email'];
$varPhone=$row['Phone'];
$varUtilities=$row['utilities'];
$varTermLease=$row['TermLease'];
$varNotes=$row['Notes'];
$image1=$row['imageName1'];
$image2=$row['imageName2'];
$image3=$row['imageName3'];
$image4=$row['imageName4'];
}
}
If the link you are using is only fetching the last record in the database table, then the underlying query that is used must be fetching the last record instead of the intended record. Am I correct in understanding the problem you are having? That any link you use is just returning the last record in the database?
Posting a code snippet will help the community take a closer look.
in your php file, you run a query for all records, but ...
$record_id = mysql_real_escape_string($_GET["record_id"]);
$query="SELECT * FROM propertyinfo WHERE id=$record_id";
your link needs to attach a parameter that will allow you to query for a specific record.
a href="outputtest.php&record_id=8"
AND you would also want to check what is in the GET parameter before sticking it into the query! I know mysql_real_escape_string is outdated.

Dynamic url or pages in php

Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

Categories