So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>
Related
I am making e-commerce site and add to basket script not doing anything
I expect it to insert data into shopping basket from products page that is working perfectly fine. Please have a look and help me figure it out.. it is not giving any syntax error or parse error it just dont do anything and when I click buy it just redirect me to homepage
<?php
error_reporting(E_ALL);
session_start();
require("db.php");
require("functions.php");
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$prodres = mysqli_query($prodsql);
$numrows = mysqli_num_rows($prodres);
$prodrow = mysqli_fetch_assoc($prodres);
if($numrows == 0)
{
header("Location: " . $config_basedir);
} else {
if($_POST['submit'])
{
if($_SESSION['SESS_ORDERNUM'])
{
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", "
. $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
if($_SESSION['SESS_LOGGEDIN'])
{
$sql = "INSERT INTO orders(customer_id, registered, date) VALUES("
. $_SESSION['SESS_USERID'] . ", 1, NOW())";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM']
. ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
} else {
$sql = "INSERT INTO orders(registered, date, session) VALUES("
. "0, NOW(), '" . session_id() . "')";
mysqli_query($sql);
session_register("SESS_ORDERNUM");
$_SESSION['SESS_ORDERNUM'] = mysqli_insert_id();
$itemsql = "INSERT INTO orderitems(order_id, product_id, quantity) VALUES("
. $_SESSION['SESS_ORDERNUM'] . ", " . $_GET['id'] . ", "
. $_POST['amountBox'] . ")";
mysqli_query($itemsql);
}
}
$totalprice = $prodrow['price'] * $_POST['amountBox'] ;
$updsql = "UPDATE orders SET total = total + "
. $totalprice . " WHERE id = "
. $_SESSION['SESS_ORDERNUM'] . ";";
mysqli_query($updres);
header("Location: " . $config_basedir . "showcart.php");
} else {
require("header.php");
echo "<form action='addtobasket.php?id="
. $_GET['id'] . "' method='POST'>";
echo "<table cellpadding='10'>";
echo "<tr>";
if(empty($prodrow['image']))
{
echo "<td><img src='./productimages/dummy.jpg' width='50' alt='"
. $prodrow['name'] . "'></td>";
} else {
echo "<td><img src='./productimages/" . $prodrow['image']
. "' width='50' alt='" . $prodrow['name']
. "'></td>";
}
echo "<td>" . $prodrow['name'] . "</td>";
echo "<td>Select Quantity <select name='amountBox'>";
for($i=1;$i<=100;$i++)
{
echo "<option>" . $i . "</option>";
}
echo "</select></td>";
echo "<td><strong>£"
. sprintf('%.2f', $prodrow['price'])
. "</strong></td>";
echo "<td><input type='submit' name='submit' value='Add to basket'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
}
}
require("footer.php");
error_reporting(E_ALL);
?>
there are two redirects that makes your user return to your home page
first:
$validid = pf_validate_number($_GET['id'], "redirect", $config_basedir);
make sure $_GET['id] has valid value
second:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
$numrows = mysqli_num_rows($prodres);
// ...
if($numrows == 0)
{
header("Location: " . $config_basedir);
}
check your query in this line:
$prodsql = "SELECT * FROM products WHERE id = " . $_GET['id'] . ";";
make sure it returns not an empty results ( $numrows == 0 )
Test it first on your DBMS front-end
I want to echo sql database records in my page and I am using this code. When I run it doesn't display the result from the db. I have records in the database that match the criteria. I am new in php and sql so please tell where I have mistakes.
session_start();
if (!isset($_SESSION['name'])) {
header('Location:vhod.php');
exit;
}
$pageTitle = 'СЪОБЩЕНИЯ';
include 'includes/header.html';
$email = $_SESSION['email'];
$name = $_SESSION['name'];
include 'php/db_connect.php';
$msgs = '';
$query = 'SELECT `timestamp`, `to`, `sender`, `subject`, `msg` FROM msg WHERE `to`="$name"';
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row["timestamp"] . " >> От: " . $row["sender"] . " >> Тема: " . $row["subj"] . " >> Съобщение: " . $row["msg"] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}
try modifying the lower part of your code like this.
$msgs = '';
$query = "SELECT * FROM msg WHERE to=$name";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row['timestamp'] . " >> От: " . $row['sender'] . " >> Тема: " . $row['subj'] . " >> Съобщение: " . $row['msg'] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}
Trying to pull data out of a basic phpmyadmin database.
The code below pulls the data correctly (Commented out section verify).
I can write it to the screen and display it. (Not needed just testing)
Trying to insert it into another database however and it fails.
I've discovered that the while loops for inserting do not run. Although I can not find out why.
It's a basic localhost database (Testing right now) So the connect data is just temporary.
Any assistance is greatly appreciated
Thanks.
<?php
/*
Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
$questions = mysqli_query($webcon, "SELECT * FROM questions");
$scenarios = mysqli_query($webcon, "SELECT * FROM scenarios");
$results = mysqli_query($webcon, "SELECT * FROM results");
$employees = mysqli_query($webcon, "SELECT * FROM employees");
/*
* These while loops display the content being pulled from the database correctly.
while ($row = mysqli_fetch_array($questions)) {
echo $row['questionID'] . " : " . $row['question'] . " : " . $row['answers'];
echo "</br>";
}
while ($row = mysqli_fetch_array($scenarios)) {
echo $row['scenarioID'] . " : " . $row['scenarioTitle'] . " : " . $row['scenarioInformation'];
echo "</br>";
}
while ($row = mysqli_fetch_array($results)) {
echo $row['employeeID'] . " : " . $row['scenarioID'] . " : " . $row['questionID'] . " : " . $row['answers'] . " : " . $row['correct'];
echo "</br>";
}
while ($row = mysqli_fetch_array($employees)) {
echo $row['employeeID'] . " : " . $row['firstName'] . " : " . $row['lastName'] . " : " . $row['email'] . " : " . $row['password'];
echo "</br>";
}
*/
/* //////////////////////////////////////////////////////////////////////////
Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
/*
*
*/
while ($row = mysqli_fetch_array($questions)) {
mysqli_query($mobcon, "INSERT INTO questions (questionID, question, answers) VALUES (" . $row['questionID'] . ", " . $row['question'] . ", " . $row['answers'] . ")");
}
while ($row = mysqli_fetch_array($scenarios)) {
mysqli_query($mobcon, "INSERT INTO scenarios (scenarioID, scenarioTitle, scenarioInformation) VALUES (" . $row['scenariosID'] . ", " . $row['scenarioTitle'] . ", " . $row['scenarioInformation'] . ")");
}
while ($row = mysqli_fetch_array($results)) {
mysqli_query($mobcon, "INSERT INTO results (employeeID, scenarioID, questionID, answers, correct) VALUES (" . $row['employeesID'] . ", " . $row['scenariosID'] . ", " . $row['questionID'] . ", " . $row['answers'] . ", " . $row['correct'] . ")");
}
while ($row = mysqli_fetch_array($employees)) {
mysqli_query($mobcon, "INSERT INTO employees (employeeID, firstName, lastName, email, password) VALUES (" . $row['employeesID'] . ", " . $row['firstName'] . ", " . $row['lastName'] . ", " . $row['email'] . ", " . $row['password'] . ")");
}
/*
Close Connections
*/
mysqli_close($webcon);
mysqli_close($mobcon);
/*
* Error code:
Notice: Undefined index: scenariosID on line 75
Notice: Undefined index: employeesID on line 78
Notice: Undefined index: scenariosID on line 78
Notice: Undefined index: employeesID on line 81
*/
?>
The problem is that you close your $webcon connection and then you try to read from it ^^
You try to do this... Thats not possible ;)
Prepare query mysqli_query($webcon, "SELECT * FROM questions");
Close connection <<< after that i cant read data
Read data
Try this please.
<?php
/**
* Connect to database
*/
$webhost = 'localhost';
$webusername = 'root';
$webpassword = '';
$webdbname = 'transfertest';
$webcon = mysqli_connect($webhost, $webusername, $webpassword, $webdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions`');
$scenarios = mysqli_query($webcon, 'SELECT * FROM `scenarios`');
$results = mysqli_query($webcon, 'SELECT * FROM `results`');
$employees = mysqli_query($webcon, 'SELECT * FROM `employees`');
/**
* Connect to database
*/
$mobhost = 'localhost';
$mobusername = 'root';
$mobpassword = '';
$mobdbname = 'exampletransfer';
$mobcon = mysqli_connect($mobhost, $mobusername, $mobpassword, $mobdbname);
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`questionID`, `question`, `answers`) VALUES ('" . $row['questionID'] . "', '" . $row['question'] . "', '" . $row['answers'] . "');");
}
// scenarios
while ($row = mysqli_fetch_array($scenarios))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `scenarios` (`scenarioID`, `scenarioTitle`, `scenarioInformation`) VALUES ('" . $row['scenariosID'] . "', '" . $row['scenarioTitle'] . "', '" . $row['scenarioInformation'] . "');");
}
// results
while ($row = mysqli_fetch_array($results))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `results` (`employeeID`, `scenarioID`, `questionID`, `answers`, `correct`) VALUES ('" . $row['employeesID'] . "', '" . $row['scenariosID'] . "', '" . $row['questionID'] . "', '" . $row['answers'] . "', '" . $row['correct'] . "');");
}
// employees
while ($row = mysqli_fetch_array($employees))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `employees` (`employeeID`, `firstName`, `lastName`, `email`, `password`) VALUES ('" . $row['employeesID'] . "', '" . $row['firstName'] . "', '" . $row['lastName'] . "', '" . $row['email'] . "', '" . $row['password'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);
Pending it's on the same server and using the same username and password:
// Create a new MySQL database connection
if (!$con = mysql_connect('localhost', $username, $password)) {
die('An error occurred while connecting to the MySQL server!<br/>' . mysql_error());
}
if (!mysql_select_db($database)) {
die('An error occurred while connecting to the database!<br/>' . mysql_error());
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!mysql_query($query)) {
die('A MySQL error has occurred!<br/>' . mysql_error());
}
}
}
If using MySQLi instead of MySQL:
// Create a new MySQL database connection
if (!$con = new mysqli('localhost', $username, $password, $database)) {
die('An error occurred while connecting to the MySQL server!<br/>' . $con->connect_error);
}
// Create an array of MySQL queries to run
$sql = array(
'DROP TABLE IF EXISTS `exampletransfer.questions`;',
'CREATE TABLE `exampletransfer.questions` SELECT * FROM `transfertest.questions`'
);
// Run the MySQL queries
if (sizeof($sql) > 0) {
foreach ($sql as $query) {
if (!$con->query($query)) {
die('A MySQL error has occurred!<br/>' . $con->error);
}
}
}
$con->close();
We have a script that generate invoice once a month (cron). But we would like to add feature, that we would be able to select date range "from - to" and then generate invoice only for the date selected.
I guess making input fields with calendar pop-up isn't hard, but filtering with PHP is a bit bigger challenge, so if anyone want to take a look at my code and give me some tips, I would be grateful.
function genInvoice($clientID, $orderID=0, $paid=false)
{
if($orderID == 0)
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and status='closed' and tblusers.clientid=" . $clientID;
else
$sql = "select tblorders.* from tblorders,tblusers where invoiceid=0 and tblorders.userid=tblusers.id " .
"and tblusers.clientid=" . $clientID . " and tblorders.id=" . $orderID;
$res = full_query($sql) or die(mysql_error());
// If no closed orders uninvoiced, just return
if(!mysql_num_rows($res))
return 0;
$amount = 0;
$orders = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
// print_r($row);
// print "<br><hr>";
$amount += $row['amount'];
$orders[] = $row['id'];
}
$date = date("Y-m-d");
$status = $paid ?'Paid' : 'Unpaid';
$sql = "insert into tblinvoices (clientid, date, duedate, subtotal, total, status) values (" . $clientID . ",'" . $date .
"','" . $date . "'," . $amount . "," . $amount . ",'" . $status . "')";
$res = full_query($sql) or die(mysql_error());
$invoiceid = mysql_insert_id();
$sql = "update tblorders set invoiceid=" . $invoiceid . " where id in (" . implode(",", $orders) . ")";
$res = full_query($sql) or die(mysql_error());
$sql = "select tblorders.id as ReportID, FirstName, LastName, SearchName, CountyID, StateID, bl_orderitems.userid, bl_orderitems.amount, " .
"bl_orderitems.notes from tblorders, bl_orderitems left join bl_search on bl_search.id=packageid where tblorders.id in (" .
implode(",", $orders) . ") and bl_orderitems.orderid=tblorders.id order by tblorders.id,bl_orderitems.id";
$res = full_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
if($row['CountyID'] != 0)
$locale = getCounty($row['CountyID']);
else if($row['StateID'] != 0)
$locale = getState($row['StateID']);
if($row['SearchName'] != "")
$description = mysql_real_escape_string($row['FirstName'] . " " . $row['LastName'] . " " .
$row['SearchName'] . " " . $locale . " (Order #" . $row['ReportID'] . ")");
else
$description = "Search Package: " . mysql_real_escape_string($row['notes'] . " (Order #" . $row['ReportID'] . ")");
$sql = "insert into tblinvoiceitems (invoiceid, userid, type, description, amount, duedate) values " .
"(" . $invoiceid . "," . $row['userid'] . ",'search','" . $description . "','" .
$row['amount'] . "','" . $date . "')";
// print $sql . "<br>";
full_query($sql) or die(mysql_error());
}
sendmessage ('Invoice Created', $invoiceid);
return $invoiceid;
}
not going to look through all that code, but filtering results by a date range is easy.
SELECT id FROM some_table WHERE some_date_field BETWEEN $first_date AND $second_date
I am trying to use json_encode() in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
The output of this is
{"response":"lastUserID lastUser lastXPos lastYPos"}
I want it to be...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
etc.
So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks
Try:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
Change this
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
to
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
Push each user to an array:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));