I am fetching a query which has a delete button next to it. I want that the first query should never get deleted and so for the first query which is displayed should not have delete button. Here is my code.
<ul>
<?php
require('connect.php');
$gettheid = $_GET['id'];
$query = "SELECT * FROM `shoppinglist` WHERE items='".$gettheid."'";
if ($result = $conn->query($query)) {
while($row = $result->fetch_object()){
$id = $row->srno;
$item = $row->items;
$image = $row->image;
?>
<li>
<div class="intheline">Delete</div>
<div class="thumbnail intheline">
<img src="photo/<?php echo $image; ?>" />
</div>
<div class="intheline">Name of the item: <?php echo $item; ?></div>
</li>
<?php } } ?>
</ul>
I do not want below mentioned line to get displayed on the first record.
<div class="intheline">Delete</div>
Help will be appreciated :)
The Solution
The actual solution here is only 4 new lines of code.
Before the while loop, we declare a variable called $count, which will hold which iteration we are on in the loop.
$counter = 0;
At the end of the loop, but before closing it, we add 1 to the $counter variable, this means 1 will be added for every iteration in the loop.
$counter++;
Now, we just surround the delete <a> element with an IF statement, checking if $counter is not 0. If $counter is anything except 0, it will show the link.
if($counter != 0) {
echo "<a href='itemdelete.php?delete={$id}'>Delete</a>";
}
MAJOR SECURITY RISK
I can not stress enough how insecure your query is.
Little Bobby says you may be at risk for SQL Injection Attacks. Learn about Prepared Statements with parameterized queries. I recommend PDO, which I wrote a class for to make it extremely easy, clean, and more secure than using non-parameterized queries. Also, This article may help you choose between MySQLi and PDO
It is very important that you fix this security issue, no matter how big your application is (or is not). I highly urge you to fix this for this query, and any other queries you may have in your application AS SOON AS POSSIBLE.
Above, I linked to a PDO class that I made. PDO is generally a better tool than mysqli_*, as it supports many different types of databases. I believe it is more highly regarded by a lot of developers. Even if you do not with to use my class or another class, I highly recommend you switch over to PDO anyways.
Complete code
<ul>
<?php
require('connect.php');
$gettheid = $_GET['id'];
//this query has some serious security risks, anyone can alter a $_GET variable to be anything
//meaning they can interact with your database in ways you did not want. Including deleting any row
//or even entire tables easily.
$query = "SELECT * FROM `shoppinglist` WHERE items='".$gettheid."'";
//the actual solution is a counter, so you need to create a variable to hold how many rows you have gone through.
$counter = 0;
if ($result = $conn->query($query)) {
while($row = $result->fetch_object()){
$id = $row->srno;
$item = $row->items;
$image = $row->image;
?>
<li>
<div class="intheline">
<?php
//if counter is not 0, display the delete link
if($counter != 0) {
echo "<a href='itemdelete.php?delete={$id}'>Delete</a>";
}
?>
</div>
<div class="thumbnail intheline">
<img src="photo/<?php echo $image; ?>" />
</div>
<div class="intheline">Name of the item: <?php echo $item; ?></div>
</li>
<?php
//add 1 to $counter for every iteration, so only the first iteration it will be equal to 0.
$counter++;
}
}
?>
</ul>
I would like to display a group of elements in a row in php from mysql database. I already did it, but my data appears in one long column. I would like every new element to appear one next to the other.
Here is a screenshot of what I get. I would like to the first one to be next to the second one:
https://www.dropbox.com/s/2y3g0n7hqrjp8oz/Capture.PNG?dl=0
Here is my code:
<?php
require_once 'core/init.php';
include 'includes/navigation.php';
$sql = "SELECT * FROM interviews WHERE featured = 1";
$featured = $db->query($sql);
<html>
enter code here
enter code here
<link href="http://localhost/menu/css/academy.css" rel="stylesheet" `enter code here`type="text/css" />
<?php while($product = mysqli_fetch_assoc($featured)) : ?>
<table>
<tr>
<th>
<div id="element1"></div>
<div id="content1">
<img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>">
<h4><?= $product['title']; ?></h4>
<hr>
<p class="description"><?= $product['description']; ?></p>
<!--------BUTTON 3-------->
<div id="hovers">
<a href="#" class="button">
<span class="contentbut"> Read More</span>
</a>
</div>
</th>
</tr>
</table>
<?php endwhile; ?>
</div>
</div>
Please, help.
Thank you!
Introduction
Note: This answer details creating a many-records-to-one-row arrangement. However, this answer can be altered to provide a single-record-to-one-row arrangement.
Separating concerns will help you write cleaner code. Separating concerns will make it easier to maintain your code. Clean code is loosely coupled, unburdened by embedded dependencies. Clean code identifies its dependencies in function signatures and class constructors with the expectation that these needs will be fulfilled externally. Clean code has tight cohesion. This means functions/methods have a single task, and classes have a single objective. Clean code is often reflected in a task that has been broken down and refined (but, not always). Clean code is an ideal I strive for, but no one is perfect.
Try to think of ways to get as much SQL and PHP out of your HTML files. Interpolating variables and showing the return results of functions only can make your HTML much easier to read. Good HTML structure counts, too.
Breaking down the task of dynamically building a <table> based on the results of a SQL query is very possible. Eventually, you may decide to use CSS and divs for styling and responsiveness reasons. This code can be altered to achieve this (after all, you'd just be stacking boxes in rows).
Eventually, creating an OOP class (with custom namespaces) would be great for modularizing your code and getting the vast majority of your symbols (variable names, etc) out of the global namespace.
Before we get going: php.ini: include_path
Do you want to setup a logical directory architecture for your project?
Set the include_path inside of php.ini.
If you search your php.ini for the include_path setting, you can set this to one directory, or any group of appropriate directories. This way, you can arrange your files in directories the way you desire, and your include, include_once, require, and require_once statements will still find the files they want to import. You will not have to type absolute paths like/dir/dir/file.php or relative paths like ../../core/database.php. In both cases, you could just specify the filename.
Example:
include 'file.php'; //Finds the file if it is in the include_path.
require 'database.php'; //Finds the file if it is in the include_path.
Note: Keep library files and other pure PHP coding files (etc ...) out of the webroot, or any publicly accessible directories. Keep them logically above the webroot. Set the include_path so you do not have to keep doing ../../blah/foo all of the time.
Tasks
1) First, make a function for getting an instance of a mysqli_result object.
/**
* Returns a string, or
* throws an UnexpectedValueException, otherwise.
*/
function isString($string)
{
if (!is_string($string)) {
throw new UnexpectedValueException("$string must be a string data type.");
}
return $string;
}
/**
* Returns a mysqli_result object, or throws an `UnexpectedValueException`.
* You can reuse this for other SELECT, SHOW, DESCRIBE or EXPLAIN queries.
*/
function getMySQLiResult(MySQLi $db, $sql)
{
$result = $db->query(isString($sql));
if (!($result instanceof mysqli_result)) {
throw new UnexpectedValueException("<p>MySQLi error no {$db->errno} : {$db->error}</p>");
}
return $result;
}
2) Second, make a function to house your SQL and invoke getMySQLiResult().
/**
* Make sure you can get the data first.
* returns a mysqli_result object.
*/
function getInterviews(MySQLi $db)
{
$sql = "SELECT * FROM `interviews` WHERE `featured` = 1";
return getMySQLiResult($db, $sql);
}
3) Make a function for building a table data (<td></td>) cell and its content. Put all HTML or data that you need to repeat for each record in here.
/**
* Returns one database table record a table data cell.
*/
function buildCell(array $record)
{
return "<td>\n".
'<img src="' .$record['image']. '" alt="' .$record['title']. '">' ."\n".
'<h4>' .$record['title']. '</h4>' . "\n" .
'<hr>' . "\n" .
'<p class="description">' .$record['description']. '</p>' . "\n" .
'<div id="hovers">
<a href="#" class="button">
<span class="contentbut">Read More</span>
</a>
</div>' . "\n
</td>\n";
}
4) Make a function for building table rows. Be wary of partial rows. :-)
First, a little helper function.
/**
* Returns one <tr></tr> element. Helper.
*/
function makeTr($tds)
{
return "<tr>\n" .isString($tds). "\n</tr>";
}
Second, the real deal.
function buildTableRow (array $tableRow)
{
return makeTr(buildCell($tableRow)) . "\n"; //Done!
}
/**
* Returns a string of multiple <tr></tr> elements,
* $maxRecords per row.
*/
function buildTableRows(array $tableRows, $numRecords, $maxPerRow)
{
$rows = []; // Holds finished groups of <tr>s
$row = ''; // Temporary variable for building row of <td>s
$numCells = 0; // Number of cells currently in a row of <td>s.
$numRows = (int)($numRecords / $maxPerRow); //Rows to make.
$numStragglers = $numRecords % $maxPerRow; // Extra <td>s, partialRow.
if ($numStragglers !== 0) { //Check if extra row is needed.
$numRows += 1;
}
foreach ($tableRows as $record)
{
$row .= buildCell($record);
++$numCells;
if ($numCells === $numRecords) { // Builds partial, last row, if needed.
$rows[] = makeTr($row);
break; // Done!
}
if ($numCells === $maxPerRow) { // Builds full row.
$rows[] = makeTr($row); // Save the row.
$numCells = 0; // Start cell counter over.
$row = ''; // Start a new row.
}
}
if(count($rows) !== $numRows) { //Verify all rows were created.
throw new RuntimeException("Rows (<tr>) for all records were not created!");
}
return implode("\n", $rows) . "\n"; //Return all rows as a string.
}
5) Make a function that spits out the HTML you need on your page. In this case, you only need one (1) substitution to appear in the HTML.
/**
* returns a set of HTML table rows (<tr></tr>) to fill a <tbody>.
* or, returns an alternative message.
*/
function drawInterviews(MySQLi $db, $maxPerRow) //PDO is recommened. Dependency injection.
{
$defaultMessage = "<tr>\n<td>There are no featured interviewers.<td>\n<\tr>\n";
try {
if (!is_int($maxPerRow) || $maxPerRow < 1) {
throw new RangeException("The number of interviews per row must be an integer equal to 1, or greater than 1.");
}
//Make a robust connection sequence, or pass it in like above.
//$db = new mysqli('host', 'user', 'password', 'dbname');
$result = getInterviews($db);
$numRecords = result->num_rows;
if ($numRecords < 1) {
return $defaultMessage;
}
if ($numRecords === 1) {
return buildTableRow($result->fetch_assoc());
}
return buildTableRows($result->fetch_all(), $numRecords, $maxPerRow);
} catch (Exception $e)
//Something went wrong with the query.
error_log($e->getMessage());
} finally { //PHP 5.5+
$result->free();
}
return $defaultMessage;
}
6) Now, have a good HTML <table> structure. Only one interpolation needed. Assuming three <td>s (records) per row ...
Anyway, if you want a table, put a copy of this table "skeleton" inside of academytest.php, somewhere between the header and the footer (i.e. the main <body> of the HTML document).
<table>
<caption>Featured Interviewers</caption> <!-- Centers above table. -->
<thead>
<tr> <!-- If needed. -->
<th>Heading1</th> <!-- If needed. -->
<th>Heading2</th> <!-- If needed. -->
<th>Heading3</th> <!-- If needed. -->
</tr>
</thead>
<tfoot></tfoot> <!-- If needed. Yes, it goes after <thead>. -->
<tbody>
<!-- <div id="element1"></div> --> //What goes between here?
<!-- <div id="content1"> --> //What's this?
<?= drawInterviews($db, 3); ?> <!-- Dependency injection. -->
</tbody>
</table>
All of this can be made more modular and reusable (object-oriented, even).
Update:
Based on your Dropbox code ...
academytest.php
1) The best thing to do is create a separate PHP file named tbodyFiller.php, or something to that effect. Put all the functions in this file, except for getInterviews() and drawInterviews() which will go into academyLibray.php, isString() which will go into library.php, and getMySQLiResult() which will go in database.php (formerly init.php).
The beginning of academytest.php should look like this:
<?php
// academytest.php
require '../../includes/library.php'; //For now, put generic helper functions here. Group them, later.
require_once '../../core/database.php'; //Formerly, init.php. Put getMySQLiResult() in here.
require '../../includes/academyLibrary.php'; //Put the two "interview" functions here.
$db = getMySQLi(); //Many things are dependent on this being here.
require '../../includes/navigation.php';
/***************** DELETE THESE LINES *****************/
//$sql = "SELECT * FROM interviews WHERE featured = 1";
//$featured = $db->query($sql);
/******************************************************/
In the footer of academytest.php, close the connection to your database.
<!-- ------FOOTER------ -->
<?php
include '../../includes/footer.php';
$db->close(); //Ensures $db is available to use in the footer, if necessary.
?>
library.php
The beginning of library.php should look like this:
<?php
// library.php
/**
* Returns a string, or
* throws an UnexpectedValueException, otherwise.
*/
function isString($string)
{
if (!is_string($string)) {
throw new UnexpectedValueException("$string must be a string data type.");
}
return $string;
}
I think init.php should be named database.php. You can learn to use the object oriented constructor (using new) sequence with error checking at your leisure. Eventually, you will want to learn PDO.
Also, make a separate file to hold your credentials. Right now, this is better than hard coding them in to the getMySQLi() function.
dbCreds.php
<?php
// dbCreds.php
$host = ''; //IP or DNS name: string.
$username = ''; //Your account: string.
$passwd = ''; //The password: string.
$dbname = ''; //The database you want to work with: string.
//*************************************************************************
//$port = '3306'; //Un-comment and change only if you need a differnt TCP port.
//Also, you would need to add a $port as your last argument in new MySQLi(),
//in the getMySQLi() function.
database.php
<?php
// database.php
/**
* Returns a mysqli_result object, or throws an `UnexpectedValueException`.
* You can reuse this for other SELECT, SHOW, DESCRIBE or EXPLAIN queries.
*/
function getMySQLiResult(MySQLi $db, $sql)
{
$result = $db->query(isString($sql));
if (!($result instanceof mysqli_result)) {
throw new UnexpectedValueException("<p>MySQLi error no {$db->errno} : {$db->error}</p>");
}
return $result;
}
function getMySQLi() //This can be improved, but that's not the issue right now.
{
require_once 'dbCreds.php'; //Choose your own file name. Do not put in public directory.
$db = new mysqli($host, $username, $passwd, $dbname); //$port would be next.
if(!($db instanceof MySQLi)){
throw new UnexpectedValueException("A MySQLi object was not returned during your connection attempt.");
}
if(isset($db->connect_error)){
throw new UnexpectedValueException("The database connection was not established. {$db->connect_errno} : {$db->connect_error}");
}
return $db
} //Using the object form of MySQLi object has side benenfits.
academyLibrary.php
The beginning of academyLibrary.php should look like this:
<?php
// academyLibrary.php
require 'tbodyFiller.php'; //Put all but four functions in here.
function getInterviews(MySQLi $db)
{
$sql = "SELECT * FROM `interviews` WHERE `featured` = 1";
return getMySQLiResult($db, $sql);
}
/**
* Comments //etc...
*/
function drawInterviews(MySQLi $db, $maxPerRow)
{
//The code, etc ...
}
If you have not configured your include_path inside of the php.ini, make sure academyLibrary.php and tbodyFiller.php are located in the same directory.
navigation.php
We are going to replace the procedural forms of working with MySQL with the object-oriented ones. This is simple, and we do not need to change much. I will not replace your loops or queries at this time, but my advice is to get out of the habbit of putting PHP loops and SQL directly in your HTML. Find a way to use a function or method, like I did for the table's in academytest.php. By this time, you should have enough examples. :-)
Refactoring
I took some time to refactor this file. Here is what I have at the top. Once again, you may wish to create another PHP file, say navLibrary.php, and put these functions into it. In that case you would replace all the functions seen below with one line, require 'navLibrary.php';. Naturally, this way of importing code may depend on configuring your include_path inside of the php.ini.
<?php
// navigation.php
function getPqueryMainData(MySQLi $db)
{
$sql = "SELECT * FROM `mainmenu` WHERE `parent` = 0"; //pqueryMain
return getMySQLiResult($db, $sql);
}
function getPqueryData(MySQLi $db)
{
$sql = "SELECT * FROM `categories` WHERE `parent` = 0"; //pquery
return getMySQLiResult($db, $sql);
}
function getCquery1Data(MySQLi $db)
{
$sql = "SELECT * FROM `categories` WHERE `parent` = 1"; //cquery1
return getMySQLiResult($db, $sql);
}
function getCquery2Data(MySQLi $db, $int)
{
$sql = "SELECT * FROM `categories` WHERE `parent` = '$int'"; //cquery2
return getMySQLiResult($db, $sql);
}
//Consider doing at most 3 queries early on.
//Consider using better names for your variables.
//I get that 'p' means "primary", and 'c' means "child", but come on. :-)
$pqueryMain = getPqueryMainData($db);
$pquery = getPqueryData($db);
$cquery1 = getCquery1Data($db);
$cquery2 = null;
There are few issues with your code, such as:
You're creating a new table in each iteration of while() loop.
You're using the same div ids, element1 and content1 for all of your table rows. Use class instead. However, based on your question,
I would like every new element to appear one next to the other.
You can use the id attributes there, but you have to take the entire <table> ... <div id="content1"> and <div id="hovers"> ... </table> out of the while() loop. And of course, change id="hovers" to class="hovers" and the associated CSS accordingly.
So the solution code would be like this:
<table>
<tr>
<div id="element1"></div>
<div id="content1">
<?php
while($product = mysqli_fetch_assoc($featured)){
?>
<td>
<img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>">
<h4><?= $product['title']; ?></h4>
<hr>
<p class="description"><?= $product['description']; ?></p>
<!--------BUTTON 3-------->
<div class="hovers">
<a href="#" class="button">
<span class="contentbut"> Read More</span>
</a>
</div>
</td>
<?php
}
?>
</div>
</tr>
</table>
Update(1):
From OP's comment,
I am trying to have 3 interviews in a row and several rows with interviews.
The solution would be to have three table cells in each row,
<table>
<div id="element1"></div>
<div id="content1">
<tr>
<?php
$counter = 1;
while($product = mysqli_fetch_assoc($featured)){
if($counter % 4 == 0){
echo '</tr><tr>';
}
++$counter;
?>
<td>
<img src="<?= $product['image']; ?>" alt="<?= $product['title']; ?>">
<h4><?= $product['title']; ?></h4>
<hr>
<p class="description"><?= $product['description']; ?></p>
<!--------BUTTON 3-------->
<div class="hovers">
<a href="#" class="button">
<span class="contentbut"> Read More</span>
</a>
</div>
</td>
<?php
}
?>
</tr>
</div>
</table>
I have a SQL query in my code that I want to convert to a prepared statement to stop vulnerabilities like SQL injections. So this is what I want to convert:
<?php
$query = "SELECT * from `wp_posts` WHERE ID=$pid ";
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_fetch_array($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
This is what I tried, but it doesn't work.
$query = "SELECT * from `wp_posts` WHERE ID=? ";
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
$result = mysqli_query($link, $query);
//$id=$row['Gallery_Id'];
while($row = mysqli_stmt_fetch($result)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
Almost all the examples online doesn't use the procedural method I use. How can I rectify this?
To protect your query against injection attack, you have two options. The first is super simple and just as secure as a prepared statement.
Cast $pid as an integer.
$query = "SELECT post_title, post_content FROM wp_posts WHERE ID = " . (int)$pid;
Secure and done.
How to write a prepared statement with result binding... (I don't use procedural mysqli syntax)
if (!$stmt = $link->prepare("SELECT post_title, post_content FROM wp_posts WHERE ID = ?")) {
echo "Syntax Error # Prepare"; // $link->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("i", $pid) || !$stmt->execute() || !$stmt->bind_result($title, $content)) {
echo "Syntax Error # ParamBind | Execute | ResultBind"; // $stmt->error; <-- never show actual error details to public
} else {
while ($stmt->fetch()) {
echo "<div>";
echo "<h2 align=\"cente\">$title</h2><br>";
echo "<div class=\"paracenter\">";
echo "<p id=\"cont\">$content</p>";
echo "<hr color=\"black\" width=\"10%\">";
echo "</div> ";
}
}
Some additional notes.
If you are not going to use result binding, you should use mysqli_fetch_assoc() instead of mysqli_fetch_array(). mysqli_fetch_array() will generate a bloated result set of both indexed and associative keyed elements (double what you actually need).
When you use bind_result(), you need to replace * in the SELECT clause with the columns to be extracted.
My first elseif() expression contains three separate calls & checks on $stmt. As soon as any one of those calls returns a falsey/erroneous response, the conditional expression short circuits and the remaining calls in the expression are never executed.
If adopting my object-oriented mysqli style, be sure to align your database connection syntax as object-oriented as well.
I am trying to fetch data from the database, but not retrieve data particular id.
this is my one page:
example1.php
<a style="color: #3498DB;" class="btn btn-default" href="http://www.example.com/getafreequote?id=<?php echo $row['product_id']; ?>">Get Quote</a>
example2.php
<?php
$id = isset($_GET['id'])?$_GET['id']:'';
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
while ($fetch1 = mysql_fetch_object($run1)){
?>
<div class="col-xs-12 col-sm-6">
<label for="GetListed_product"></label>
<input class="le-input" name="product" id="GetListed_product" type="text" value="<?php
$b = $fetch1->product_id;
$q2 ="SELECT product_id,name FROM oc_product_description WHERE product_id = $b";
$q3 = mysql_fetch_assoc(mysql_query($q2));
echo $q3['name'];
?>" >
<span id="productmsg" class="msg"></span>
</div>
<?php
}
?>
</div>
but didnot get data form particular product id. I have got error show like this
Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in example.com/example2.php on line 71
Please don't use mysql functions they are deprecated. Use mysqli or PDO for database operations. Also the way you write the query string makes it easy for an SQL injection, use prepared statements instead. Here is an example:
$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch();
You can also use prepared statements for inserting or updating data. More examples here
As said by FilipNikolovski, don't use mysql functions they are deprecated. Use mysqli or PDO for database operations.
For your problem, the function mysql_query is returning false. The query is not returning any result and thus mysql_query is returning false.
Make a check like this:
$query = "SELECT * FROM oc_product_description WHERE product_id=$id";
$run1 = mysql_query($query);
if($run1)
{
if(mysql_num_rows($run1) > 0)
{
while ($fetch1 = mysql_fetch_object($run1))
{
// your stuff here
}
}
else
{
echo "No records found.";
}
}
else
{
echo "Error in query : ".mysql_error();
}
This will help you to detect the problem and to solve as well.
I have been trying for a while to figure out how to display data from a specific row within my database based on the ID.
Say I want the link to be survivaloperations.net/page/mso?p=contracts&id=#
where id=# is the ID of the row I am pulling data from in the database
How would I pull and display data from the database using a link like shown above?
I Tried to google it, but didn't really know what to google to find related things
Any help or links for references are appreciated!
Here is what I had tried:
<?php
if ($p == contracts) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
if ($id != 0):
// I assume this is a specific news item meaning you know it's ONE result
$query = 'SELECT * FROM contracts WHERE id=' . $id . ' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
endif;
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while ($row = mysql_fetch_array($result)) {
// and use'em however you wish
echo("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row2[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a
href='#'>$row2[unit]</a><br/>by: <a
href='http://www.survivaloperations.net/user/$row2[userid]-$row2[username]/'>$row2[username]</a>
</div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row2[callsign]<br/>
Urgency: $row2[urgency]<br/>
Location: $row2[location]<br/>
Grid: $row2[grid]<br/>
Enemy Activity: $row2[enemy_activity]<br/>
Hours Since Lasrt Contact: $row2[contact_hours]<br/><br/>
Supplies Requested: $row2[supplies]<br/>
Comments: $row2[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
?>
I figured it out with my original code:
if ($p == contracts)
{
$cid = $_GET['id']; // if $_GET['id'] exists, return it as an integer, otherwise use a sentinel, id's usually start with 1, so 0 works
$query = 'SELECT * FROM contracts WHERE id='. $cid .' LIMIT 1'; // so try to use limit 1, no need to add extra steps in the database lookup
mysql_select_db('survival_contracts');
$result = mysql_query($query);
//$result = mysql_query($query) or die(mysql_error());
// now loop through the results
while($row = mysql_fetch_array($result)){
// and use'em however you wish
echo ("<div class='mso_body_wrap'>
<div id='mso_news_container'>
<div class='mso_news_wrap'>
<div class='mso_news_top'>$row[contract_type]</div>
<div class='mso_news_poster'>
<div class='mso_poster_avatar'><img src='images/tank.jpg'></div>
<div class='mso_poster_info'>for <a href='#'>$row[unit]</a><br />by: <a href='http://www.survivaloperations.net/user/$row[userid]-$row[username]/'>$row[username]</a></div>
</div>
<div class='mso_news_content'>
<div class='mso_news_body'>
Callsign: $row[callsign]<br />
Urgency: $row[urgency]<br />
Location: $row[location]<br />
Grid: $row[grid]<br />
Enemy Activity: $row[enemy_activity]<br />
Hours Since Lasrt Contact: $row[contact_hours]<br /><br />
Supplies Requested: $row[supplies]<br />
Comments: $row[comments]
</div>
</div>
<div class='mso_news_bottom'></div>
</div>
</div>");
}
Google for $_GET variable in PHP and have a look at database connection using PDO or mysqli
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/pdo.query.php
After you added code:
mysql_* is deprecated. Try to switch to either mysqli or PDO and have a look at the link above.
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT) ? abs( (int) $_GET['id']) : 0;
if($id == 0) {
echo 'Invalid ID';
return;
} else {
$query = "SELECT * FROM `table` WHERE `id`=". $id;
$get = $db->prepare($query);
if($get) {
$get = $db->query($query);
$r = $get->fetch_array(MYSQLI_ASSOC);
var_dump($r);
} else {
echo 'Could not connect to the database';
return;
}
I've mixed two styles of MySQLi, which isn't really standard, but it should suffice for this example.
http://php.net/mysqli
(Ensure you have database connection)
$row2 should be $row
And things like
$row[contract_type]
Better to be
$row['contract_type']
And try to move to mysqli or PDO as advised by earlier poster