I created Joomla articles with content and forms representing a quiz. Users fill in the forms, actually their answers and then submit it.
After that, the congratulation.php page opens (code below) and my database gets filled with data. It should fill in columns like id and answer. But the problem is that I cannot achieve my id variable, that should point on the article id of the article where the quiz was.
<?php
echo 'WELL DONE!!!<br/>';
$answer1 = $_POST['answer1'];
$db =& JFactory::getDBO();
$query = "INSERT INTO quiz(id, answer1)
VALUES ((select id from jos_content where title='$title'), '$answer1')";
$db->setQuery($query);
$db->query();
?>
HOW to define $title variable. The $title variable should be for example "Pet's quiz". I can do it manually, but how to create this to recognize the article and put the title of it in mysql.
Related
I'm creating a webpage that loads a random product from one table (the "Products" table) from my database every time the page reloads. The logged in user (the user must be logged in) can choose to add that product to their personal favorites or not (stored in the "Favorites" table). Every time the user clicks the corresponding button to add that product to their favorites the webpage reloads and shows another new random item. The problem is that the webpage probably reloads before the query is executed, so the 'new' item is added to their favorites instead. Does anyone know how I can solve this? This is what I got so far:
HTML
<form method="get">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
PHP
header("Cache-Control: no-cache, must-revalidate");
session_start();
include_once 'dbconnect.php';
$user_id = ($_SESSION['user']);
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites(user_id,product_id)
VALUES('$user_id','$aRow[product_id]')";
$result = mysql_query($SQL);
}
Well, actually your PHP code only gets a random item and then saves it if the user clicked like. You should output the product ID on the form like this:
<form method="get">
<input type="hidden" name="current_product_id" value="<?php echo $productid; ?>">
<button type="submit" name="like">
<img class="add-to-favorites" src="image.png">
</button>
</form>
Where <?php echo $productid; ?> has the ID of the new random product.
Your PHP should go in this order and with these values:
if(isset($_GET['like'])){
$SQL = "INSERT INTO Favorites (user_id,product_id) VALUES ('$user_id','$_GET[current_product_id]')";
$result = mysql_query($SQL);
}
$sSQLQuery = "SELECT product_id FROM Products ORDER BY RAND()";
$aResult = mysql_query($sSQLQuery);
$aRow = mysql_fetch_array($aResult, MYSQL_ASSOC);
$productid = $aRow['product_id'];
So now, if you click on like, the $_GET['current_product_id'] will have the current product and then I output the new random product ID in the hidden input so that the next item works too!
Also: important, consider using mysqli_* functions instead of mysql_* functions because these last ones are deprecated :)
Your problem is that when the page refreshed, you first get new data from the Database and then save the old data - which is replaced by the new data.
Obviously you need to transfer the old product-id in the GET-Parameters. There are many options to do this, for example creating a hidden field.
echo "<input type=\"hidden\" name=\"oldProductId\" value=\"$productid\">
You can then access it when the page reloads with
$_GET['oldProductId']
and write it to the favorites-table.
Firstly, PDO... Always :P.
But to answer your question, you need to send the product_id along with $_GET['like'], so you know which product they selected. Since you're randomly selecting one from the database on every load.
In its current state, that is your best option.
But please consider moving to PDO especially since you mention logged in users and products.
How can I prevent SQL injection in PHP?
*Link credits to Sean (comment)
I want to list the contents of a 'name' column from an sql table on a HTML/PHP web page. This page currently allows me to create records, but is there a way of listing the records by name only, and displaying them somewhere specific on the HTML page?
The comments didn't seem to answer 100% to my knowledge so maybe this broad answer might help.
If you want to grab all the names located in a specific SQL table first make sure to connect to your database using
mysql_connect('SERVER', 'USER', 'PASSWORD');
mysql_select_db('DATABASENAME');
After you have connected you ran run queries to your database as stated. For your example it would be something like this:
//Query to get values
$query= mysql_query("SELECT name FROM TABLE_NAME");
//Places all query results into an array "row"
while($row = mysql_fetch_assoc($query)){
//Prints values as though it were HTML
echo $row['name']."<br>";
}
Here's an example of getting one name back from the users table and storing it in a variable to use later in the page.
<?php
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$name = $result['name'];
?>
<div class="greeting">Hello <?php echo $name; ?></div>
In a more advanced case you can also store variables in sessions (cookies) so that you can use them throughout your website (including subdomains) without having to re-query the database each time
<?php
session_start();
$query = mysql_query("SELECT name FROM Users");
$result = mysql_fetch_array($query);
$_SESSION['name'] = $result['name'];
?>
Now whenever you want to grab the variable you just got from the query simple do <?php $_SESSION['name']; ?> Just make sure that you have session_start() at the top of the page (my suggestion is place in a header file and include the header file in all pages)
Make sure your file is a .php file and you place the code about in the proper <?php ?> tags
if my question appears to be silly but I ran out of explanations.
I'm trying to set up a page with some news on it. I have the database with such attributes like News_id, news_header, news body etc.
I have 2 pages first page gives a list of the brief descriptions of the news with the button which allows user to read some more of a particular news on it. If clicked it passes a corresponding news_id value to the page 2 which fetches News_Id Value, queries corresponding values from database value and outputs the content.
The problem is that no mater which button in the list of page 1 I click to see news, the page 2 always receives the news_id value of the news which is *first in the lin*e. here are the codes
PAGE ONE (the list)
<form name='NewsLineSelection' method='post' action='news.php'>
<?php
$News_Query = "Select * from news order by Date_Posted Desc;";
$GetNews = mysql_query( $News_Query, $IVE_Connection ) or die("ERROR: ".mysql_error());
while ( $News_Database = mysql_fetch_array( $GetNews ) ){
?>
<tr><td ><?php echo $News_Database[1]; ?></td>//header
<tr><td ><?php echo $News_Database[2]; ?></td>//news body
...etc
<tr><td class="maintext">
<input type='hidden' name='NewsToRead' value='<?php echo $News_Database[0]; ?>'>//News_ID is here
<input type='submit' name='AddNews' value='Read More...' >
</td></tr>
}//end of the loop
Page 2 (with info details)
$News_id = addslashes($_POST['NewsToRead']);
$News_Query = "Select * from news where news_id = ".$News_id.";";
$GetNews = mysql_query( $News_Query, $Connection ) or die("ERROR: ".mysql_error());
$News_Database = mysql_fetch_row( $GetNews );
//Then output the query's content
It looks perfect on paper. But I really can't understand why if there are 10 news in the list of page 1 for instance, no matter which button I click the value of $News_id in PAGE 2 will be always the id of the first news in the list on the page 1.
May be I don't see something. it suppose to work ok, but it doesn't.
Thanks for any kind of help or suggestions.
That's because you're having multiple inputs with the same name. You're looking at the problem wrong.
You're fetching (getting) data, you should be using a GET request, and not a POST request.
My recommendation, that each News headline would be wrapped in a link like so:
<h1>
<a href="news.php?id=<?php //Code to output the correct ID here ?>"><?php //Code to output the correct headline here ?>
</a>
</h1>
A few things extra
Don't use tables for laying out your page! Tables are meant for table data. Use correct semantic elements: (<h1> for important headlines, <h2> for less important headlines, <p> for paragraphs, and so on).
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.
Afternoon,
Wondering if anyone can help me. Using tables in a database I've got a form which is pre populated (from the content in the database) depending on the page the user has come in from when an enquiry is made.
Eg. if the user has come in from product A page and clicked on the 'enquiry' button from item c, the enquiry form is already pre populated with the name 'product A' and 'item c'
index.php?id=1&pack=13
This is fine if the user comes in from a product page, however if the user clicks on the enquiry button at a higher level page how do I get just the product name to appear in the form? I would have thought it would have been as simple to just change the code to
index.php?id=1
However that doesn't work - the form is completing blank when doing this.
My php knowledge is very limited therefore any help is hugely appreciated.
The db table I'm wanting to target is say 'Bob', within this table I want to target the id of the individual items which selects the name of the item. This currently works as:
$query = mysql_query("SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id AND Bob.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
However I now only want 'Bob.Name' for this particular 'enquiry' link. My brain is frying!!
Many thanks,
Motley
Hi Dalionzo,
Thanks for your reply. However not really sure if it does help me out. In the current enquiry php page I have:
<?php {
$query = mysql_query("SELECT Bobs.Name, Bob_Packages.Name FROM Bobs, Bob_Packages WHERE Bobs.Id=Bob_Packages.Bob_Id AND Bobs.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
$result = mysql_fetch_array($query);
echo $result[0];
}
?>
It's basically just the Bobs.Id I want pulling through. I gave what you supplied a try and an error was returned.
Any ideas? Thanks very much.
In your query you're checking for
id=$id AND packages.id=$pack
This means, that if the query is missing one from the URL, it won't find anything at all!
So, what you have to do, is check if one of them is missing, and then create different queries using that
<?php
$query = "SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id";
if($_GET['id'] != '') {
$query .= " AND Bob.ID = '".$id."'";
}
if($_GET['pack'] != '') {
$query .= " AND Bob_Packages.Id = '".$pack."'";
}
mysql_query($query);
?>
Hope this helps you out!
P.S. I haven't tested this...