trouble getting mysql array to duplicate code to execute per each row - php

im trying to query the database and apply code to each result and insert a record per result to a databse. This code works but only does it for the last result row. Ive tried foreach but cannot get it to work most likley because i dont understand how it should work. Please help and thank you
<?php
if(isset($_POST['bill1'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require ('dbconnect.php');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
$invoicedate= $_POST['invoicedate'];
$invoiceduedate= $_POST['invoiceduedate'];
echo 'post is good';
require ('dbconnect.php');
echo 'db connect';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM customer WHERE terms = 1");
while($row = mysqli_fetch_array($result)) {
echo 'array good';
$item = $row['inputItem'];
$itemdescription = $row['description1'];
$itemprice = $row['itemprice1'];
$id = $row['id'];
$paidstatus = 5;
$totaldue = $itemprice;
require ('dbconnect.php');
echo $item;
echo $itemdescription;
echo $itemprice;
echo $id;
echo $paidstatus;
echo $invoicedate;
echo $invoiceduedate;
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt)){
$addone = "1";
$invoicenewnumber = $addone + $row [invoice_number];
}
echo $invoicenewnumber;
//echo $row [invoice_number];
$invoice_number = $invoicenewnumber;
require ('dbconnect.php');
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
if (!mysqli_query($con,$put))
die('Error: ' . mysqli_error($con));
echo 'succsess';
}
?>

<?php
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt))
{
$addone = "1";
$invoicenewnumber = $addone + $row [invoice_number];
$invoice_number = $invoicenewnumber;
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
}
?>

Try this insert the second query in the while loop.
And read the comment where ever you find them in the Answer
Note:You need the connection only one time in whole page.
<?php
if(isset($_POST['bill1']))
{mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
require ('dbconnect.php'); You need the connection only once
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}}
$invoicedate= $_POST['invoicedate'];
$invoiceduedate= $_POST['invoiceduedate'];
echo 'post is good';
//require ('dbconnect.php'); Dont need here
// echo 'db connect'; Dont need here
//if (mysqli_connect_errno()) {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
$result = mysqli_query($con,"SELECT * FROM customer WHERE terms = 1");
while($row = mysqli_fetch_array($result)) {
echo 'array good';
$item = $row['inputItem'];
$itemdescription = $row['description1'];
$itemprice = $row['itemprice1'];
$id = $row['id'];
$paidstatus = 5;
$totaldue = $itemprice;
require ('dbconnect.php');
echo $item;
echo $itemdescription;
echo $itemprice;
echo $id;
echo $paidstatus;
echo $invoicedate;
echo $invoiceduedate;
$resulttt = mysqli_query($con,"SELECT invoice_number FROM invoices ORDER BY invoice_number DESC LIMIT 1");
while($row = mysqli_fetch_array($resulttt)){
$addone=$addone+1;//If you want to add one to the invoice number you have to use this.
$invoicenewnumber = $addone + $row ['invoice_number'];//}//remove the closing while loop from here,
//Added quete to the Invoice_number
echo $invoicenewnumber;
//echo $row [invoice_number];
$invoice_number = $invoicenewnumber;
require ('dbconnect.php');
$put = mysqli_query($con,"INSERT INTO invoices (item, description, item_total, id, paidstatus, duedate, invoicedate, invoice_number, total_due)VALUES('$item', '$itemdescription', '$itemprice', '$id', '$paidstatus', '$invoiceduedate', '$invoicedate', '$invoice_number', '$totaldue')");
}
if (!mysqli_query($con,$put))
die('Error: ' . mysqli_error($con));
echo 'succsess';
}
?>

Related

How to show average from mysql

How to show the average of a column in mysql?
Below is my code which i have tried so far :
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
// Input
$sql = "SELECT AVG(column_name) FROM table_name";
// Check age
if ($age > 99 or $age < 5) {
echo ("We only store data of people between the age of 5 and 99.");
if (!mysqli_query($conn, $sql)) {
die('Error: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
}
else {
echo ("We got it!");
}
// Close connection
((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
die();
?>
But how to exactly define a variable to the result of the AVG with a maximum of 2 decimals?
I want to used and show it into another file (so I will include this one).
What I have right now
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/opendb.php");
// My own created code
$sql = $conn->query("SELECT ROUND(AVG(price AS FLOAT), 2) FROM data WHERE age= '$age'");
$data = $sql->mysqli_fetch_assoc();
$avg_data = $data['price'];
echo $avg_data;
// This below is from an other post but don't know how it works and if it is good.
$ratings = $conn->query("SELECT AVG(price) avg_rating FROM data form_id = '" . $age . "'");
$data2 = $ratings->mysqli_fetch_assoc();
$avg_rating = $data2['avg_rating'];
echo $avg_rating;
die();
?>
Use Like This For Getting Average witth two decimal points.
$sql = "SELECT ROUND(AVG(column_name AS FLOAT), 2) FROM table_name";
How I fixed it:
<?php
if (isset($_GET["age"])) {
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT AVG(price) FROM data WHERE age= '$age'") or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo $row['AVG(price)'];
echo number_format($row['AVG(price)'], 2);
}
die();
}
else {
echo 'Something went wrong, try again.';
}
?>
$sql = 'SELECT *, ROUND(AVG(column_name), 2) AS avg_value FROM table_name';
avg_value will store the rounded + average value and add * if need to get all the column.

Is it possible to assign sql table value to a variable in php?

Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

mysql_num_rows returning zero

<?php
session_start();
$con=mysql_connect("localhost","root","samy");
mysql_select_db("project");
if($con)
{
echo "Connected Successfully ";
}
else
{
echo "Error" . $sql . "<br>" . mysql_connect_error();
}
$name=$_SESSION['name'];
echo $name;
$sql1 = mysql_query("select cust_id from registered_user where name ='.$name.' ");
$r = mysql_num_rows($sql1);
echo $r;
$row1 = mysql_fetch_array($sql1);
$cid = $row1['cust_id'];
echo $cid;
?>
Since num_rows is returning zero therefore $cid is also not printing.
Don't know what's the error;
You should remove the dot(.).
$sql1 = mysql_query("select cust_id from registered_user where name ='$name'");
^ ^
Also suggest to add error reporting like this
$sql1 = mysql_query("select cust_id from registered_user where name ='$name'")
or die(mysql_error());

php insert sql issue while loop / foreach

The following code from my data between tables, but for some reason only one value is inserted to database
<?php
DEFINE("DB_SERVER", "localhost"); //LOCALHOST
DEFINE("DB_USER", "user");
DEFINE("DB_PASS", "pass");
DEFINE("DB_NAME", "table");
$connect = mysql_connect(DB_SERVER,DB_USER,DB_PASS) or die("connect issue". ' ' . mysql_error());
mysql_query('SET NAMES utf8');
$db = mysql_select_db(DB_NAME,$connect) or die("connect issue". ' ' . mysql_error());
mysql_query('SET NAMES utf8');
if (!$db){
echo "connect issue";
}
$sql = "SELECT id, column2 FROM tablea";
$result = mysql_query($sql) or die(mysql_error());
$set = date("Y-m-d H:i:s", time());
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$list = $row['column2'];
echo "user_id: $id";
echo "<br/><br/>";
$makes = explode (";", $row['column2']);
$i = 0;
foreach ($makes as $make) {
$sql2 = "SELECT url FROM tableb WHERE id = '$make'";
$result2 = mysql_query($sql2) or die(mysql_error());
while ($row2 = mysql_fetch_array($result2)) {
echo $row2[0];
echo $row2[1];
echo $row2[2];
echo $row2[3];
echo $row2[4];
echo $row2[5];
echo $row2[6];
echo $row2[7];
$m1 = $row2[0];
$m2 = $row2[1];
$m3 = $row2[2];
$m4 = $row2[3];
$m5 = $row2[4];
$m6 = $row2[5];
$m7 = $row2[6];
$m8 = $row2[7];
echo "<br/>";
}
if (++$i == 8) break;
}
$sql3 = "INSERT INTO tablec (partner_id, make1, make2, make3, make4, make5, make6, make7, make8, saved) VALUES ('$id', '$m1', '$m2', '$m3', '$m4', '$m5', '$m6', '$m7', '$m8', '$set')";
$result3 = mysql_query($sql3) or die(mysql_error());
var_dump($sql3);
var_dump($result3);
if($result3) {
echo "done";
}
else {
echo "fail";
}
echo "<pre>";
var_dump($row);
echo "</pre>";
echo "<hr/>";
}
?>
var_dump sql:
string(186) "INSERT INTO tablec (partner_id, make1, make2, make3, make4, make5, make6, make7, make8, saved) VALUES ('75', 'opel', '', '', '', '', '', '', '', '2014-02-06 18:20:14')"
it works fine, but the only 1 variable inserted the table "$row2[0];"
whats the problem? thank you for your help!
You only ever fetch one field from your tableb:
$sql2 = "SELECT url FROM tableb WHERE id = '$make'";
^^^^---- here
If you want more fields, you need to specify them:
SELECT url, field1, field2, etc...

Categories