I am creating a PHP shopping cart linked to SQL database, from a tutorial i am following.
The code below SHOULD display all my products, however I believe that the
$id = intval($_GET['id']);
section is messing it up. The SKU's of the products are Varchar, not integers, so I am lead to believe that this is causing the problem with "intval". Is there another datatype I can insert that will display my products again?
<?php
if (isset($_GET['action']) && $_GET['action'] == "add")
{
$id = intval($_GET['id']);
if(isset($_SESSION['cart'][$id]))
{
$_SESSION['cart'][$id]['quantity']++;
}
else
{
$sql2 = "SELECT * FROM products WHERE SKU={$id}";
$query2 = mysql_query($sql2);
if(mysql_num_rows($query2) != 0)
{
$row2 = mysql_fetch_array($query2);
$_SESSION['cart'][$row2['SKU']] = array("quantity => 1, "price" => $row['price']);
}
else
{
$message = "This product id is invalid";
}
}
}
?>
<h2 class="message"><?php if(isset($message)){echo $message; ?></h2>
<h1>Product Page</h1>
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$sql = "SELECT * FROM products ORDER BY SKU ASC";
$query = mysql_query($sql)or die(mysql_error());
while($row = mysql_fetch_assoc($query))
{
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['Description']; ?></td>
<td><?php echo "£" . $row['price']; ?></td>
<td>Add to Cart</td>
</tr>
<?php
}
?>
</table>
You are missing an ending quote here:
$_SESSION['cart'][$row2['SKU']] = array("quantity" => 1, "price" => $row['price']);
You're also missing a } sign
<h2 class="message"><?php if(isset($message)){echo $message; } ?> </h2>
Check the docs for intval() and you'll see that this method returns 0 when the variable isn't an integer.
if you're looking to search for this, you can just change the line to:
$id = $_GET['id'];
to get the variable as a string
However there are two things to bear in mind with this:
This is liable to lead to sql injection vulnerabilities if not treated properly in your code
The mysql_ functions are deprecated, and shouldn't be used in new code... there're a number of good tutorials and debates on the matter... use PDO or mysqli
Related
I'm trying to delete a row from a MySQL table using PHP. I have visited many pages already but I can't find a reason why I can't make it work.
Contacts.php
require_once "functions.php";
$db = new DatabaseConnection();
$user = new AddressBook($db->pdo);
<table>
<tr>
<th>Nombre</th>
<th>Telefono</th>
<th>Direccion</th>
<th>Email</th>
</tr>
<?php
$i=0;
$contactos=$user->verContactos();
foreach($contactos as $conts){
$i++;
?>
<tr>
<td><?php echo $conts['nombre']; ?></td>
<td><?php echo $conts['telefono']; ?></td>
<td><?php echo $conts['direccion']; ?></td>
<td><?php echo $conts['email']; ?></td>
<td>Borrar</td></tr>
</tr>
<?php } ?>
</table>
delete.php
<?php
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$result = mysql_query("DELETE FROM contacts WHERE id=$id")
or die(mysql_error());
header("Location: contacts.php");
}
else
{
header("Location: contacts.php");
}
?>
I know you're gonna say mysql is not useful anymore. In my web system I have this part using a function and PDO extension.
It doesn't matter if I use this example or my version using PDO, I cannot get the id. I just get something like this:
http://localhost/agenda/borrar.php?id <- Missing ID
The id field in database is called 'id'. I think the problem may be the use of $_GET but I can't find it.
This:
<td>Borrar</td></tr>
Needs to be this:
<td>Borrar</td></tr>
And this:
$result = mysql_query("DELETE FROM contacts WHERE id=$id")
Needs to be this:
$result = mysql_query("DELETE FROM contacts WHERE id=" . intval($id))
Here is my database:
Here is the code that I tried:
<?php
//---DB Connection---
//---FIND ALL AMBANK RECORD---
$q = "SELECT *
FROM mtid
WHERE provider = Ambank";
$r = mysqli_query($dbc, $q);
//---CREATE TABLE---
echo '<table border="1" style="border-collapse:collapse">';
echo '<tr>';
echo '<th>Serial No</th>';
echo '<th>Feat A?(Y/N)</th>';
echo '<th>Feat B?(Y/N)</th>';
echo '<th>Feat C?(Y/N)</th>';
echo '<th>Feat D?(Y/N)</th>';
echo '</tr>';
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
//---FIND FEATURE ID---
$q1 = "SELECT feat_ID
FROM functionfeatures
WHERE sNo = '".$row['sNo']."' && mmID = '".$row['mmID']."' &&
ttID = '".$row['ttID']."'";
$r1 = mysqli_query($dbc, $q1);
//---[HERE]---
echo '<tr>';
echo '<td>'.$row['sNo'].'</td>';
...
echo '</tr>';
}
echo '</table>';
?>
I want to make a table like below:
This table is consists of 5 fields, which is serial number, feature A, feature B, feature C, feature D. From my database, serial number 11-11-11-11 have feature B, feature C, feature D. Thus, I want to display No on feature A, Yes on the feature B, feature C and feature D in table.
However, I am stuck on how to compare the feature ID and display Yes/No on the feature name.
How should I continue from the [HERE] section?
Can someone help me please?
You can use only one query for that:
$query = "SELECT
m.sNo,
f.feat_name,
CASE
WHEN ff.sNo IS NULL THEN 'No'
ELSE 'Yes'
END AS yesno
FROM
mtid m
JOIN features f
LEFT JOIN functionfeatures ff ON ff.feat_ID = f.ID AND ff.sNo = m.sNo
WHERE provider = 'Ambank'
ORDER BY
m.sNo,
f.feat_name";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$sNo = '';
echo '<table border="1">
<tr>
<td>sNo</td>
<td>Feat A</td>
<td>Feat B</td>
<td>Feat C</td>
<td>Feat D</td>
</tr>
<tr>';
while($row = mysqli_fetch_array($result)){
if($sNo != $row['sNo']){
if($sNo != '') echo '</tr><tr>';
echo '<td>'.$row['sNo'].'</td>';
$sNo = $row['sNo'];
}
echo '<td>'.$row['yesno'].'</td>';
}
echo '</tr>
</table>';
Output is:
Try this:
while($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
// set default values
$array = array(
"1" => "NO",
"2" => "NO",
"3" => "NO",
"4" => "NO"
);
$q1 = "SELECT feat_ID
FROM functionfeatures
WHERE sNo = '".$row['sNo']."' && mmID = '".$row['mmID']."' &&
ttID = '".$row['ttID']."'";
$r1 = mysqli_query($dbc, $q1);
// if we have a feat_ID match - set its value in the array to YES
while($row1 = mysqli_fetch_array($r1, MYSQLI_ASSOC))
{
$array[''.$row1['feat_ID'].''] = "YES";
}
echo '<tr>';
echo '<td>'.$row['sNo'].'</td>';
// output the values for each function ID
foreach ($array as $yesno) {
echo '<td>'.$yesno.'</td>';
}
echo '</tr>';
}
I would approach it a bit different. Using JOINs as mentioned but also separating the code to separate your front-end from back-end (Read up on The MVC Pattern):
Your back-end handles the data, obtains the SQL results and builds the array needed for the front-end:
<?php
// $dbc is set in your ---DB Connection---
$sql = "SELECT m.sNo, f.feat_name, ff.feat_ID
FROM mtid m
JOIN features f
LEFT JOIN functionfeatures ff ON ff.feat_ID = f.ID AND ff.sNo = m.sNo
WHERE provider = 'Ambank'
ORDER BY m.sNo, f.feat_name";
$result = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
$yes_no_feats = [];
while ($row = mysqli_fetch_assoc($result)) {
$yes_no_feats[$row['sNo']][] = $row;
}
mysqli_close($dbc);
?>
As you can see the variable $yes_no_feats holds the result which is then passed to the front-end so that it can then be parsed with HTML:
<table border="1">
<tr>
<th>Serial No</th>
<th>Feat A</th>
<th>Feat B</th>
<th>Feat C</th>
<th>Feat D</th>
</tr>
<?php
foreach ($yes_no_feats as $sno => $features) {
?>
<tr>
<td><?= $sno ?></td>
<?php foreach ($features as $f) { ?>
<td><?= (!empty($f['feat_ID'])) ? "Yes" : "No" ?></td>
<?php } ?>
</tr>
<?php
}
?>
</table>
Hope this helps.
I am having this weird problem.
There are seven admins: darth, jane, luke, najin, root, sam and sydney.
CODE:
<table>
<tr>
<th style="text-align: left; width: 200px;">Username</th>
<th colspan="2" style="text-align: left;">Action</th>
</tr>
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
$admin = mysqli_fetch_assoc($result);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
</table>
If I use ASC order, the first admin, darth is not displayed in the loop and if I use DESC order, the last admin, sydney doesn't show up.
What could be the problem here?
Get rid of the first $admin = line.
Your loop will fetch all of them; you don't need to fetch the first one separately (and if fact by doing so are skipping it, because your loop immediately fetches the second before the first one could be written out).
remove this line
$admin = mysqli_fetch_assoc($result);//You already fetching the first result here
You have a redundant call to $admin = mysqli_fetch_assoc($result); before the while loop which will cause you to skip the first row of the result. Just remove it and you should be fine.
<?php
$sql = "SELECT * FROM admins ORDER BY Admin_Username ASC";
$result = mysqli_query($connection, $sql);
while($admin = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo ($admin["Admin_Username"]); ?></td>
<td>Edit</td>
<td>Delete</td>
</tr>
<?php
}
?>
$admin = mysqli_fetch_assoc($result);
This must be in while loop So you can descard/remove old value above while
I have a mysql table, one of its columns called parking space has a number in it. However, for some records the 'parking space'-column is empty. Now, I want to call just this column in a page table where the column heads are numbered from 1 - 200 (first column: 1; second column: 2;....) So, if there is the value '12' in the 'parking space'-column, then this shall show up in column '12' and so on, and if there is no entry for a number then the column in the page table shall be left empty. How can I associate the numbers in 'parking space' with that page table?
...
<?php
$pagetable=array('1','2','3','4','5','6');//...until 200
foreach($pagetable as $value){
?>
<table border="1px" cellspacing="1" cellpadding="1">
<tr>
<th>
<?php echo $value ?>
</th>
</tr>
<?php
}
include("dbinfo.inc.php");
include_once("config.php");
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0){
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$park=mysql_result($result,$i,"park");
?>
<tr>
<td style="background-color:;">
<?php echo $park; ?>
<br>
<?php if($park!=''){ ?>
<?php echo $id; ?>
<?php
}
?>
</td>
</tr>
<?php
$i++;
}
}
?>
...
There are two ways, you can do this.
Create all 200 rows on the database table and query it. This will omit almost all of the headache to get what you want.
Do a for loop from 1 to 200 and compare the active item if it exists on the mysql results. For this you require an continuous numeric entry in the database to identify each columns individually.
What I mean is? Column 1 in the should have corresponding record indicating 1 somewhere in its record.
Here is an example of this:
$result = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results = mysql_num_rows($result);
if ($results > 0) {
$num=mysql_numrows($result);
$rows = array();
while($row = mysql_fetch_row($result)) {
$rows[$row['id']] = $row;
});
//Now process it
}
Try this:
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts ORDER BY park ASC");
$results_count = mysql_num_rows($result);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space): ?>
<td><?php echo $space ?></td>
<?php end foreach ?>
</tr>
<tr>
<?php foreach ($parks as $park): ?>
<td><?php if ($park > 0) { echo "$space"; } else { echo " "; } ?></td>
<?php end foreach ?>
</tr>
</table>
Start with this and tell me what you get.
Ok, I got it changed a little. Now it ahows me all from 1-200 and it shows the parking spaces values, but these values are not associated with the numbers. it looks to me like it puts them according to the id, for example in my table the customer on parking space 165 has the id 4 and therefore it doesnt put 165 to 165 but 165 to 4
<?php
include("dbinfo.inc.php");
include_once("config.php");
$spaces = range(1, 200);
$results = mysql_query("SELECT * FROM contacts");
$results_count = mysql_num_rows($results);
if ($results_count > 0) {
for ($i = 0; $i < $results_count; $i++) {
$parks[] = mysql_result($results, $i, "park");
}
}
?>
<table>
<tr>
<?php foreach ($spaces as $space){ ?>
<td><?php echo $space; ?></td>
<?php } ?>
</tr>
<tr>
<?php foreach ($parks as $park){ ?>
<td><?php if ($park!='') { echo $park.'<br>';} else { echo " "; } ?></td>
<?php }?>
</tr>
</table>
I am new to PHP/MySQL to please bear with me. I am trying to have PHP write a table which returns a list of records from a join table. The SQL statement works perfectly when I run the query but I do not know how to write the function properly.
SQL statement which works:
SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID"
My functions:
function get_shares_by_member($member_ID) {
global $db;
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets
ON shares.asset_ID = assets.asset_ID)
INNER JOIN members
ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = $db->query($query);
$share_result = $share_result->fetch();
return $share_result;
}
function get_shares() {
global $db;
$query = "SELECT * FROM shares";
$share = $db->query($query);
$shares_table = $share->fetch();
return $share;
}
My action:
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_shares';
}
if ($action == 'list_shares') {
if (!isset($member_ID)) {
$member_ID = 0;
}
$shares = get_shares_by_member($member_ID);
$share = get_shares();
}
Here is my table:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares_table as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $share['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I know this is a lot to ask but I've been struggling with this for the past 3 days. Any help will be much appreciated! If anyone needs help with AD/Exchange, I'd be happy to share my knowledge in that area!
Thanks!!
From what I can see on here, this will produce a blank table with however many rows are returned for a number of reasons:
None of the columns returned by the get_shares_by_member function are share_ID or asset_ID, so those columns won't be filled in.
You are referencing percent_owner from $shares which, assuming is an array as you are using it in a 'foreach' loop, will need an index to reference it, or it should otherwise be $share['percent_owner']
The percent_owner field will be put in the 'asset cost' column at present as there is no blank cell produced to move it to the '% ownership' column where it would seem logical to have it.
Based on what you have posted so far, the following should suit your needs:
<table>
<tr>
<th>Nick Name</th>
<th>Asset Description</th>
<th>Asset Cost</th>
<th class="right">% Ownership<th>
<th> </th>
</tr>
<?php foreach ($shares as $share) : ?>
<tr>
<td><?php echo $share['nick_name']; ?></td>
<td><?php echo $share['asset_desc']; ?></td>
<td><?php echo $share['asset_cost']; ?></td>
<td class="right"><?php echo $shares['percent_owner']; ?></td>
<td> </td>
</tr>
<?php endforeach; ?>
</table>
I would recommend changing either the $share variable in the foreach, or the $share which is being set by get_shares(). Personally speaking, I would change the latter from
$share = get_shares();
to something like:
$shares_table = get_shares();
as it is essentially containing all of the information from the shares table, assuming the database abstraction layer function fetch() returns all results.
There could also be an issue when you are doing:
$share = $db->query($query);
$share = $share->fetch();
Going from different database abstraction layers I have seen, I would expect fetch() to be done as (using your variables)
$share = $db->fetch();
If the fetch() is requiring a result to be passed into it, then I would expect the code to look similar to:
$share_result = $db->query($query);
$share = $db->fetch($share_result);
a few points:
are you sure your query does not return any errors? If there are
errors, that might cause fetch() to fail
what DB class are you using? I would suggest that you please check
that there is a fetch() function and what parameters does it accept? For example, the fetch() may be invoked like $share_result->fetch() or $db->fetch() or $db->fetch($share_result) etc.
I might be wrong but it seems that the fetch() might be always
returning the first row from the resultset. Perhaps you might need
to do fetch() in a loop for reading all results
You may as well try using the default PHP functions. Here is a code snippet that explains how you may rewrite your functions using PHP's default mysql() library:
mysql_connect('your host', 'your user', 'your password'); function get_shares_by_member($member_ID) {
$output = Array();
$query = "SELECT members.nick_name, assets.asset_desc, shares.asset_cost, shares.percent_owner
FROM
(shares INNER JOIN assets ON shares.asset_ID = assets.asset_ID)
INNER JOIN members ON shares.member_ID = members.member_ID
WHERE shares.member_ID = $member_ID";
$share_result = mysql_query($query);
while ($row = mysql_fetch_assoc($share_result)) {
$output[] = $row;
}
return $output;
}
function get_shares() {
$output = Array();
$query = "SELECT * FROM shares";
$share = mysql_query($query);
while ($row = mysql_fetch_assoc($share)) {
$output[] = $row;
}
return $output;
}
Hope the above helps. Please feel free to let me know if there is anything that is not clear.