I have a table called incidents, that i'd like to retrieve 4 fields/columns from, but i need firstname and lastname from the customer table. I keep getting the following error:
Warning: Invalid argument supplied for foreach()
This is the relevant code:
public static function get_incidents_unassigned(){
$db = Database::getDB();
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name, incident.productCode, incident.dateOpened, incident.title, incident.description FROM incidents
INNER JOIN customers
ON incident.customerID = customer.customerID
WHERE techID IS NULL';
$statement = $db->prepare($query);
$statement->execute();
$rows = $statement->fetch();
$incidentList = array();
foreach ($rows as $row){
$incidents = new Incident(
$row['name'], $row['productCode'],
$row['dateOpened'], $row['title'], $row['description']);
$incidentList[] = $incident;
}
$statement->closeCursor();
return $incidentList;
}
******but this is the involved table
<table>
<tr>
<th>Customer</th>
<th>Product</th>
<th>Date Opened</th>
<th>Title</th>
<th>Description</th>
<th> </th>
</tr>
<?php foreach ($incidents as $incident) :
$ts = strtotime($incident->getDate_Opened());
$date_opened_formatted = date('n/j/Y', $ts);
?>
<tr>
<td><?php echo htmlspecialchars($customer->getFullName()); ?></td>
<td><?php echo htmlspecialchars($incident->getProduct_Code()); ?></td>
<td><?php echo htmlspecialchars($incident->getTitle()); ?></td>
<td><?php echo htmlspecialchars($incident->getDescription()); ?></td>
<td><?php echo $date_opened_formatted; ?></td>
<td><form action="." method="post">
<input type="hidden" name="action"
value="select_incident">
<input type="hidden" name="product_code"
value="<?php echo htmlspecialchars($incident->getIncident_id()); ?>">
<input type="submit" value="Select">
</form></td>
</tr>
<?php endforeach; ?>
</table>
//****may have been looking at too long!
You should add some error handling to your code. The db could tell you that incident is not defined. The data is selected from incidents but incident is used to identify the fields.
I mean try changing your statement to match your circumstances
$query = 'SELECT concat(customer.firstName,customer.lastName) AS name,
inc.productCode, inc.dateOpened, inc.title,
inc.description FROM incidents inc
INNER JOIN customers
ON inc.customerID = customer.customerID
WHERE techID IS NULL';
Your database is able to give you error messages. These error messages describe what is your problem with your statement
Related
I have a function in PHP that prints a list of inventories with their IDs.
Another function lists the products in the inventory with the corresponding ID from the inventory list.
But I don't know how to get the inventory ID from the list correctly into the product list, and it doesn't work for me. I don't know exactly where I'm doing wrong.
When I list the products with a specific ID and refresh the page, I want the list to stay the same.
A function to get a list
<?
php function fetchSeznamInventur() {
global $userCon;
global $rowcount;
global $query;
global $inventuraId;
global $row;
$query = mysqli_query($userCon, "SELECT * FROM seznamInventur");
//$inventuraId = $row["id"];
$rowcount = mysqli_num_rows($query);
}
?>
List listing to HTML
<?php
<table border="1" class="invTable">
<thead>
<th>Datum</th>
<th>ID</th>
<th>Název</th>
</thead>
<?php
for ($inv = 1; $inv <= $rowcount; $inv++) {
$row = mysqli_fetch_array($query);
?>
<tr>
<td><?php echo $row["createdate"]?></td>
<td name="id"><?php echo $row["id"] ?></td>
<td><?php echo $row["name"]?></td>
<td><input type="submit" name="submit" value="Detail"></td>
</tr>
<?php
}
?>
</table>
?>
Obtaining products by inventory ID
<?php
function fetchInventura() {
global $userCon;
global $inventuraId;
global $rowcount;
global $query;
$query = mysqli_query($userCon, "SELECT * FROM inv WHERE inventuraId='$inventuraId'");
$rowcount = mysqli_num_rows($query);
echo $inventuraId;
}
?>
List of products in html
<?php
for ($products = 1; $products <= $rowcount; $products++) {
$row = mysqli_fetch_array($query);
?>
<tr>
<td><?php echo $row["id"]?></td>
<td><?php echo $row["inventuraId"] ?></td>
<td style="display: none;"><?php echo $row["name"]?></td>
<td><?php echo $row["ean"]?></td>
<td style="display: none;"><?php echo $row["plu"]?></td>
<td style="display: none;"><?php echo $row["externalId"]?></td>
<td style="display: none;"><?php echo $row["productId"]?></td>
<td><?php echo $row["quantity"]?></td>
<td><?php echo $row["versiondate"]?></td>
</tr>
<?php
}
?>
</table>
<input type="submit" name="submit" value="Detail">
won't do much, as it's not inside a form.
You probably need a hyperlink which goes to a "products" page and passes the inventory ID as a query parameter, e.g.
Display
And then on the products page, you'd use $_GET["inventoryID"] to get the ID, and pass that into your SQL query (but please use a parameter, don't inject variables directly into the SQL, it's a security risk).
I have a table containing multiple rows. Behind every row is a button you can click to update a column (baatinn) in the database from 0 to 1. However when you click the button it will update all the rows from 0 to 1 instead of the row you are clicking the button on. How do i make it so it will only update the row you are clicking on
Picture of database:
HTML:
<tr>
<th>Båt ut</th>
<th>Båt inn</th>
<th>Båtnr</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Tid</th>
<th>Kr</th>
<th>Edit</th>
</tr>
PHP:
$sql = "SELECT utleid, inntid, baatnr, fornavn, etternavn, tid, kr, baatinn FROM utleie WHERE baatnr LIKE '%$sok%' or fornavn LIKE '%$sok%' or etternavn LIKE '%$sok%' or tid LIKE '%$sok%' ORDER BY id desc";
$result = $conn-> query($sql);
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
?>
<tr>
<td><?php echo $row["utleid"]; ?></td>
<td><?php echo $row["inntid"]; ?></td>
<td><?php echo $row["baatnr"]; ?></td>
<td><?php echo $row["fornavn"]; ?></td>
<td><?php echo $row["etternavn"]; ?></td>
<td><?php echo $row["tid"]; ?></td>
<td><?php echo $row["kr"]; ?></td>
<td><form method="post" action="innlevering.php">
<button name="edit" value="1">Edit</button>
</form></td>
</tr>
<?php
}
echo "</table>";
} else {
echo "0 results";
}
$conn-> close();
innlevering.php:
<?php
include_once 'dbconnect.php';
if ($_POST['edit']) {
$conn->query("UPDATE utleie SET baatinn=1");
}
?>
To help your injection problem, parameterize. It would be something like this (I use PDO, so you will want to double check):
/functions/getUtleie.php
function getUtleie($so, $conn)
{
$query = $conn->prepare("SELECT utleid, inntid, baatnr, fornavn, etternavn, tid, kr, baatinn FROM utleie WHERE baatnr LIKE ? or fornavn LIKE ? or etternavn LIKE ? or tid LIKE ? ORDER BY id desc");
$so = "%{$so}%";
$query->bind_param('ssss',$so, $so, $so, $so);
$result = $query->execute();
if($result->num_rows == 0)
return [];
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
Now, when you go to use it, include the function, then the key on the form is to make the id in a hidden field:
# Fetch the data
$result = getUtleie($so, $conn);
# If there are any results
if(!empty($result)): ?>
<table>
<?php foreach($result as $row): ?>
<tr>
<td><?php echo $row["utleid"] ?></td>
<td><?php echo $row["inntid"] ?></td>
<td><?php echo $row["baatnr"] ?></td>
<td><?php echo $row["fornavn"] ?></td>
<td><?php echo $row["etternavn"] ?></td>
<td><?php echo $row["tid"]; ?></td>
<td><?php echo $row["kr"]; ?></td>
<td>
<form method="post" action="innlevering.php">
<input type="hidden" name="action" value="update_utleie" />
<input type="hidden" name="utleid" value="<?php echo $row["utleid"] ?>" />
<input type="text" name="val" />
<input type="submit" value="Edit" />
</form>
</td>
</tr>
<?php endforeach ?>
</table>
<?php else: ?>
0 results
<?php endif ?>
After you submit the form, you will want to update using a WHERE clause:
<?php
include_once 'dbconnect.php';
# Check to make sure the form was submitted
if(!empty($_POST['action'] && $_POST['action'] == 'update_utleie') {
# Trim these. You should also check they aren't empty (especially the id)
$id = trim($_POST['utleid']);
$value = trim($_POST['val']);
$query = $conn->prepare("UPDATE `utleie` SET `baatinn` = ? WHERE `utleid` = ?");
$query->bind_param('si', $value, $id);
$query->execute();
}
Anyway, I haven't checked these scripts but it should be pretty close. Should at least point you in the right direction.
I am trying to query a database and display the results. The query is based on information from an html form. However, when I enter a name such as john in the form, for which the table has 2 entries with that name, I get 0 results. I don't know what the problem is.
Here is the html form:
<form action="cust_details_search.php" method="post">
Name :
<input type="text" name="name_search" id="name_search" >
Email :
<input type="email" name="email_search" id ="email_search" >
Phone no. :
<input type="phone" name="phone_search" id="phone_search" >
Address :
<input type="text" name="address_search" id="address_search" >
City :
<input type="text" name="city_search" id="city_search" >
State :
<input type="text" name="state_search" id="state_search" >
<br> <br>
Country :
<input type="text" name="country_search" id="country_search">
Product Enquired for :
<input type="text" name="prod_search" id="prod_search">
<input type="submit" value="Submit">
</form>
And the php file:
<?php
$server = "127.0.0.1";
$dbUsername = "root";
$dbPassword = "";
//create connection
$dbconn = new mysqli($server, $dbUsername, $dbPassword, $dbname);
$name_search = $_POST['name_search'];
$email_search = $_POST['email_search'];
$phone_search = $_POST['phone_search'];
$address_search = $_POST['address_search'];
$city_search = $_POST['city_search'];
$state_search = $_POST['state_search'];
$country_search = $_POST['country_search'];
$prod_search = $_POST['prod_search'];
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%.$name_search.%')
OR (`Phone no.` LIKE '%.$phone_search.%')
OR (`Address` LIKE '%.$address_search.%')
OR (`City` LIKE '%.$city_search.%')
OR (`State` LIKE '%.$state_search.%')
OR (`Country` LIKE '%.$country_search.%')
OR (`Product Enq. For` LIKE '%.$prod_search.%')
OR (`Email` LIKE '%.$email_search.%')");
?>
<html>
<head>
<title>Search Resutls</title>
<style>
body {
background-color: rgb(131,41,54);
}
h1 { color:#FFFFFF
}
h2 { color:#FFFFFF
}
p { color:#FFFFFF
}
</style>
</head>
<body>
<center>
<h2> Customer Details </h2>
<table style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone no. </th>
<th>Address </th>
<th>City </th>
<th>State </th>
<th>Country</th>
<th>Product Enquired for </th>
<th>Follow up details </th>
</tr>
</thead>
<tbody>
<?php
while($result = mysqli_fetch_assoc($run_query)) {
?>
<tr>
<td><?php echo $result['Name'] ?> </td>
<td><?php echo $result['Email'] ?></td>
<td><?php echo $result['Phone no.'] ?></td>
<td><?php echo $result['Address'] ?></td>
<td><?php echo $result['City'] ?></td>
<td><?php echo $result['State'] ?></td>
<td><?php echo $result['Country'] ?></td>
<td><?php echo $result['Product Enq. For'] ?></td>
<td><?php echo $result['Follow Up'] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</center>
</body>
</html>
Any help is appreciated. Thank you in advance!
You are using the PHP concatenator . but you dont need to in a double quoted string. $variables are automatically expanded in a double quoted string so try
$run_query = mysqli_query($dbconn,
"SELECT *
FROM CustomerDetails
WHERE (Name LIKE '%$name_search%')
OR (`Phone no` LIKE '%$phone_search%')
OR (`Address` LIKE '%$address_search%')
OR (`City` LIKE '%$city_search%')
OR (`State` LIKE '%$state_search%')
OR (`Country` LIKE '%$country_search%')
OR (`Product Enq For` LIKE '%$prod_search%')
OR (`Email` LIKE '%$email_search%')");
ALso some of your column names had a . in them? I assume these column names do not actually contain dots. However if the do, I suggest you remove them by editing your schema.
Your script is wide open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
Use prepared parameterized statements in either the MYSQLI_ or PDO API's
I am wanting to match my user_id column from my announcements table to the id column in my users table. I then want to get the username from the users table where the id's match.
I initially had the following query
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements"))
I am getting the following error with my current code..
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in
Which I know what this means, but do I need to add in every column table from my users table for this to work or is there another way to do this? If I do need to add all of the columns as variables in my bind_result, does it matter which order I put them in? Announcements first or users or vise versa?
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
update..
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.messages, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
The warning indicates when you are binding the result fields into variables, the number of variables does not match the number of fields in the result set:
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
The easy way around this is to always specify the fields in the SELECT statement (just an example):
SELECT t1.id, t1.user_id, t1.messages, t1.date, t2.username
Instead of:
SELECT *
My query returns the correct data when executed on the db, but when run live the company_title comes back null. All other fields work.
$row['company_name'] is the code i can't get to work:
$query = "select * from invoices i, company_lookup cl, students s where i.company_id = cl.company_id and i.student_id = s.student_id;";
$results = $DB->query($query);
$invoices = mysql_query("select * from invoices");
?>
<table border="1" id="hl" name="hl">
<tr>
<th>Month/Year</th>
<th>Full Amount</th>
<th>Company</th>
</tr>
<?php while ($row = mysql_fetch_array($invoices)) {
$invoice_date = $row['invoice_date'];
?>
<tr onMouseOver="showInvoicePayments(<? echo $row['invoice_id'] ?>);this.bgColor = '#C0C0C0'" onMouseOut ="this.bgColor = '#FFFFFF'" bgcolor="#FFFFFF">
<td><? echo date('F Y',strtotime($invoice_date)) ?></td>
<td><? echo '$' . $row['full_amount'] ?></td>
<td><? echo $row['company_name'] ?></td>
</tr>
<?
}
?>
try adding COALESCE in some of your fields.
like this one:
SELECT ..., COALESCE(company_title, ''),
COALESCE(company_name, '')
...
Instead of null value, it will return an empty string.