Inserting into database failed while expected to be inserted - php

I'm trying to insert the user and cursus id in the database on submit the current user is defined in the second part(see comment) and connection with the database is made in the require once on top of the file.
When i press the button now its echoing success but in the database noting is showing up. Console is not showing up anything and when i echo $a or &b its giving me the correct id's. What is it that im doing wrong?
<?php
session_start();
require_once('includes/mysql_config.php');
//getting user data/id
$id = isset($_SESSION['id']) ? $_SESSION['id'] : header('location: login.php');
$result = mysqli_query($con, "SELECT * FROM users WHERE id =".$_SESSION['id']);
$user = mysqli_fetch_array($result);
require_once('header.php');
$id = $_GET['id'];
$result = mysqli_query($con, "SELECT * FROM cursus c LEFT OUTER JOIN cursussoort cr ON (c.cursussoort_ID = cr.id) WHERE c.ID = $id ORDER BY c.begindatum ASC");
$amount = mysqli_affected_rows($con);
for ($i = 0; $i < $amount; $i++) {
$cursus = mysqli_fetch_array($result);
$a = $cursus['id'];
$b = $user['id'];
//$a = mysqli_real_escape_string($a);
//$b = mysqli_real_escape_string($b);
if(isset($_POST['submit'])){
if($user['id']) {
$sql = "INSERT INTO aanmeldingen (users_id, cursus_id) VALUES ('$b', '$a')";
$result = mysqli_query($sql);
echo "success";
} else {
echo "failed";
}
}
?>
<div class="main-nav">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<!-- <a class="navbar-brand" href="index.html">
<h1><img class="img-responsive" src="images/logo.png" alt="logo"></h1>
</a> -->
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="scroll active">Home</li>
<li class="scroll">Over ons</li>
<li class="scroll">Cursussen</li>
<li class="scroll">Contact</li>
<?php if(isset($_SESSION['id'])) {
echo '<li><span>Mijn account</span></li>';
echo '<li><span>Log Out</span></li>';
} else {
echo '<li><span>Log In</span></li>';
} ?>
</ul>
</div>
</div>
</div><!--/#main-nav-->
<br><br>
<!-- Post Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-preview">
<h1> <?php echo $cursus['naam_cursus'] . "<br />";?></h1>
van: <?php echo $cursus['begindatum'] . "<br />";?>
tot: <?php echo $cursus['begindatum'] . "<br />";?>
<?php echo $cursus['beschrijving'] . "<br />";?>
</div>
</div>
</div>
<form method="post">
<input type="submit" name="submit">
</form>
</div>
</div>
<?php } ?>
<hr>
If you guys need more information tell me.

With your code here:
$result = mysqli_query($sql);
mysqli_query() requires two arguments; The connection, and the query. Try replacing that with this and tell me if it fixing your issue:
$result = mysqli_query($con, $sql);
Matt

Related

PHP categories showing only one item

I'm trying to create a categories list, where user will be able to choose item with certain category, but as soon as I'm opening any of the categories, where "soon = '2'", there is only one item coming up. Everything else works.
The code bellow is for categories, where user can chose which caegory s/he want to see.
//navbar.php
<!-- Categories -->
<div class="dropdown-item menu_cat" type="button" id="catMenuButton"><i class="fas fa-caret-left"></i> Categories</div>
<form method="POST" class="dropdown-menu dropleft categories_menu row" id="cat_dropdown">
<button class="dropdown-item" name="candle"> Candles</button>
<button class="dropdown-item" name="cloth"> Clothes</button>
<button type="submit"class="dropdown-item" name="tech"> Tech</button>
</form>
Than here is everything else, that is suppose to exectute commands that will show products from category that user choose. The issue comes upp where 'if($row["soon"] == "2")' is.
//products.php
<?php
if(isset($_POST['candle'])){
$sql = "SELECT * FROM products WHERE category = 'candle'";
}else if(isset($_POST['cloth'])){
$sql = "SELECT * FROM products WHERE category = 'cloth'";
}else if(isset($_POST['tech'])){
$sql = "SELECT * FROM products WHERE category = 'tech'";
}else{
$sql = "SELECT * FROM products";
}
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
if($row["soon"] == "2"){
?>
<div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
<br>
<p>
<?php echo $row["productPrice"]; ?> SEK
</p>
<a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
<div class="row">
<button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
</div>
</a>
</div>
</div>
<?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>
<div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic_soon" src="productsImages/comingSoon.png" height="150px" width="120px"></img>
<style>
</style>
<br>
<p>
<?php echo $row["productPrice"]; ?> SEK
</p>
<a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
<div class="row">
<button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
</div>
</a>
</div>
</div>
<?php
}
}
}
else if(empty($result) || $result->num_rows == 0){
echo "<h2 class='col-12'> Sorry! </h2>";
echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
}
$conn->close();
?>
In the original post was duplicate $row = $result->fetch_assoc(); statement.
In updated post there is first condition out of the while loop.
Solution bellow is wrapping all the if($row['soon'] into the while loop:
<div class="card-deck col-lg-12 col-md-12 col-sm-12 justify-content-center text-center">
<?php
if(isset($_POST['candle'])){
$sql = "SELECT * FROM products WHERE category = 'candle'";
}else if(isset($_POST['cloth'])){
$sql = "SELECT * FROM products WHERE category = 'cloth'";
}else if(isset($_POST['tech'])){
$sql = "SELECT * FROM products WHERE category = 'tech'";
}else{
$sql = "SELECT * FROM products";
}
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){
echo "<h2 class='col-12'> Sorry! </h2>";
echo "<h3 class='col-12'> This product will be soon avaiable </h3>";
}
if($row["soon"] == "2"){
?>
<div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
<br>
<p>
<?php echo $row["productPrice"]; ?> SEK
</p>
<a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
<div class="row">
<button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
</div>
</a>
</div>
</div>
<?php
}
}
}else if($result->num_rows == 0){
echo "<h2 class='col-12'> Sorry! </h2>";
echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
}
$conn->close();
?>
</div>
}
}else if($result->num_rows == 0){
echo "<h2 class='col-12'> Sorry! </h2>";
echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
}
$conn->close();
?>
</div>
Recommendation: Always debug your scripts with enabled PHP Error Reporting!
products.php
<?php
if(isset($_POST['candle'])){
$sql = "SELECT * FROM products WHERE category = 'candle'";
}else if(isset($_POST['cloth'])){
$sql = "SELECT * FROM products WHERE category = 'cloth'";
}else if(isset($_POST['tech'])){
$sql = "SELECT * FROM products WHERE category = 'tech'";
}else{
$sql = "SELECT * FROM products";
}
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
if($row["soon"] == "2"){
?>
<div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic" src="productsImages\<?php echo $row["productID"]; ?>.jpeg" height="150px" width="120px"></img>
<br>
<p>
<?php echo $row["productPrice"]; ?> SEK
</p>
<a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
<div class="row">
<button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
</div>
</a>
</div>
</div>
<?php }else if($row['soon'] == "1" && isset($_POST['tech']) || isset($_POST['candle'])){?>
<div class="product_card col-xl-3 col-lg-4 col-md-5 col-sm-12 box-shadow">
<div class="card-header">
<h3 class="product_name my-0 font-weight-normal"> <?php echo $row["productName"] ?> </h3>
</div>
<div class="card-body">
<h2 class="card-title pricing-card-title"> </h2>
<img class="pic_soon" src="productsImages/comingSoon.png" height="150px" width="120px"></img>
<style>
</style>
<br>
<p>
<?php echo $row["productPrice"]; ?> SEK
</p>
<a class="toProduct" href="products_index.php?id=<?php echo $row['productID'] ?>">
<div class="row">
<button class="btn_to_product btn btn-lg btn-outline-dark col-lg-10 col-md-10"> Go to product <i type="button" class="fas fa-arrow-alt-circle-right"></i></button>
</div>
</a>
</div>
</div>
<?php
}
}
}
else if(empty($result) || $result->num_rows == 0){
echo "<h2 class='col-12'> Sorry! </h2>";
echo "<h3 class='col-12'> There is not any product in this category yet! </h3>";
}
$conn->close();
?>

Storing order details in MYSQL database using php

I'm trying to learn php and MYSQL through developing an eCommerce website. So far the experience with these new languages are really good, but I'm stuck on one of my ideas. I have managed to add the order details to my database, however it adds only a product at a time. Originally what I wanted to do is to add more than a product and store it in a database.
For an example let's say an user wants to buy 5 items. How can I store this into my database. With my current code this just add as a single product with the total of 5 products.(Even the quantity is not adding up).
I'm not sure whether my code is correct. Any suggestions on this is really appreciated. (Please feel free to modify code, it will be really helpful)
Following is the code I'm using to add orders to database.
<div class="col-md-12">
<h4 class="text-center">Paypal Intergration Goes Here.</h4>
<img src="./images/paywith_paypal.png" class="img-responsive center-block" alt="Pay With Paypal">
<?php
// Getting product details
$total = 0;
global $con;
$ip = getIp();
$sel_price = "SELECT * FROM zeus_limited.cart WHERE ip_address='$ip'";
$run_price = mysqli_query($con, $sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$product_id = $p_price['cart_product_id'];
$product_price = "SELECT * FROM zeus_limited.product WHERE product_id='$product_id'";
$run_product_price = mysqli_query($con,$product_price);
while ($prod_price = mysqli_fetch_array($run_product_price)){
$product_price = array($prod_price['product_price']);
$product_id = $prod_price['product_id'];
$pro_name = $prod_price['product_title'];
$values = array_sum($product_price);
$total +=$values;
}
}
// Getting Quantity from cart
$get_quantity = "SELECT * FROM zeus_limited.cart WHERE cart_product_id='$product_id'";
$show_quantity = mysqli_query($con, $get_quantity);
$row_qty = mysqli_fetch_array($show_quantity);
$quantity = $row_qty['quantity'];
if($quantity == 0){
$quantity = 1;
}
else {
$quantity = $quantity;
$total = $total * $quantity;
}
// Getting Customer details
$user = $_SESSION['customer_email'];
$get_customer = "SELECT * FROM zeus_limited.customer WHERE customer_email='$user'";
$show_customer = mysqli_query($con, $get_customer);
$row_c = mysqli_fetch_array($show_customer);
$customer_id = $row_c['customer_id'];
$customer_email = $row_c['customer_email'];
$customer_name = $row_c['customer_fname'];
$trx_id = mt_rand();
$currency = 'USD';
$invoice = mt_rand();
// Insert data to ORDER table
$add_order = "INSERT INTO zeus_limited.orders (order_product_id, order_customer_id, order_quantity, invoice_no, status, order_date) VALUES ('$product_id','$customer_id','$quantity','$invoice','in Progress',NOW())";
$run_order = mysqli_query($con, $add_order);
// Insert data to PAYMENT table
$add_payment = "INSERT INTO zeus_limited.payment (amount, payment_customer_id, payment_product_id, trx_id, payment_currency, payment_date) VALUES ('$total','$customer_id','$product_id','$trx_id','$currency',NOW())";
$run_payment = mysqli_query($con, $add_payment);
// Removing products from CART
$empty_cart = "DELETE FROM zeus_limited.cart";
$show_customerart = mysqli_query($con, $empty_cart);
if($total == $total){
echo "<div class='text-center'>";
echo "<h3>Welcome:" . $_SESSION['customer_email']. "<br>" . "Hooray! Your Payment was successful!</h3>";
echo "<a href='./customer/my_account.php'>Go to your Account</a><br>";
echo "</div>";
}
else {
echo "<div class='text-center'>";
echo "<h4>Welcome Guest, Payment process failed... Please try again</h4><br>";
echo "<a href='/shop_products.php'>Go to Back to shop</a>";
echo "</div>";
}
?>
</div>
I'm attaching the cart code as well.(if it's needed)
<?php
session_start();
require_once './includes/init.php';
require_once './functions/functions.php';
echo getCart();
?>
<!DOCTYPE html>
<html>
<head>
<title>Zeus Pvt. Ltd</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/font-awesome.min.css" />
<link rel="stylesheet" href="css/style.css" />
<meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
<script src="js/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="header">
<div class="container container-bg">
<div class="row">
<div class="col-md-4"><img src="images/logo.png" class="img-responsive" alt="Responsive image"></div>
<div class="col-md-5"></div>
<div class="col-md-3">
<div class="zeus_cart">
<div class="cart_bg">
<ul class="cart">
<i class="cart_icon"></i><p class="cart_desc"><?php getTotalCartPrice() ?><br><span class="yellow"><?php getTotalItems() ?></span></p>
<div class='clearfix'></div>
</ul>
<ul class="product_control_buttons">
<li><img src="images/close.png" alt=""/></li>
<li>Edit</li>
</ul>
<div class='clearfix'></div>
</div>
<ul class="quick_access">
<li class="view_cart">View Cart</li>
<li class="check">Checkout</li>
<div class='clearfix'></div>
</ul>
</div>
</div>
</div>
</div>
<div class="container container-bg">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand"></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Home</li>
<li class="active">Shop Products</li>
<li>My Account</li>
<li>Contact Us</li>
<li>
<?php
if(!isset($_SESSION['customer_email'])){
echo 'Login';
}
else {
echo 'Logout';
}
?>
</li>
<li class="welcome"><a>Welcome <?php echo getUsername(); ?></a></li>
</ul>
<form method="get" action="results.php" enctype="multipart/form-data" class="navbar-form navbar-right">
<div class="form-group search">
<input type="text" name="user_query" class="form-control" placeholder="Search Products">
</div>
<button type="submit" class="btn btn-default btn-search"></button>
</form>
</div>
</div>
</div>
</nav>
</div>
<div class="main">
<div class="container container-bg">
<div class="row">
<div class="col-md-12">
<div class="shoppingcart-title">
<h4 class="text-center sidebar-main-menu">Shopping Cart</h4>
<div class="table-responsive">
<form action="" method="POST" enctype="multipart/form-data">
<table class="table">
<thead>
<tr>
<th>Product No.</th>
<th>Product(s)</th>
<th>Name</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Sub Total</th>
<th>Remove</th>
</tr>
</thead>
</tbody>
<?php
global $con;
$total = 0;
$ip = getIp();
$select_price = "SELECT * FROM zeus_limited.cart WHERE zeus_limited.cart.ip_address='$ip'";
$run_price = mysqli_query($con, $select_price);
while ($product_price = mysqli_fetch_array($run_price)) {
$product_id = $product_price['cart_product_id'];
$product_quantity = $product_price['quantity'];
$product_price = "SELECT * FROM zeus_limited.product WHERE zeus_limited.product.product_id ='$product_id'";
$run_product_price = mysqli_query($con, $product_price);
while ($product_new_price = mysqli_fetch_array($run_product_price)) {
$product_price = array($product_new_price['product_price']);
$product_id = $product_new_price['product_id'];
$product_image = $product_new_price['product_image_carousel'];
$product_title = $product_new_price['product_title'];
$unit_product_price = $product_new_price['product_price'];
$values = array_sum($product_price);
$total += $values * $product_quantity;
?>
<tr>
<td><?php echo $product_id; ?></td>
<td><img src="images/products/<?php echo $product_image; ?>" </td>
<td><?php echo $product_title; ?></td>
<td><input id="" type="text" name="quantity[<?php echo $product_id; ?>]" size="5" value="<?php echo $product_quantity; ?>" style="text-align:center;"/>
<input type="hidden" name="product_id[<?php echo $product_id; ?>]" value="<?php echo $product_id; ?>"
</td>
<!--Updating the quantity-->
<?php
$ip = getIp();
if (isset($_POST['update_cart'])){
foreach ($_POST['product_id'] as $pid => $id) {
$product_id = $id;
$product_quantity = $_POST['quantity'][$pid];
$update_products = "UPDATE zeus_limited.cart SET quantity = '$product_quantity' WHERE cart_product_id = '$product_id' AND ip_address = '$ip';";
$run_update = mysqli_query($con, $update_products);
}
if($update_products){
echo "<script>window.open('cart.php','_self')</script>";
}
}
?>
<td><?php echo 'Rs '. $unit_product_price; ?></td>
<td><?php echo 'Rs '.$unit_product_price * $product_quantity ?></td>
<td><input type="checkbox" name="remove[]" value="<?php echo $product_id; ?>"/></td>
</tr>
</tbody>
<?php } } ?>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th>Grand Total: </th>
<th><?php echo 'Rs '. $total ?></th>
<th></th>
</tr>
</thead>
</table>
<div class="cart_buttons">
<input type="submit" name="update_cart" value="Update Cart"/>
<input type="submit" name="continue_shopping" value="Continue Shopping"/>
<input type="submit" name="checkout" value="Checkout"/>
<?php if (isset($_POST['checkout'])){echo "<script>window.open('checkout.php','_self')</script>"; } ?>
</div>
</form>
<?php
global $con;
$ip = getIp();
if (isset($_POST['update_cart'])){
foreach ($_POST['remove'] as $remove_id) {
$delete_product = "DELETE FROM zeus_limited.cart WHERE cart_product_id='$remove_id' AND ip_address='$ip'";
$run_delete = mysqli_query($con, $delete_product);
if($run_delete){
echo "<script>window.open('cart.php','_self')</script>";
}
}
}
if (isset($_POST['continue_shopping'])){
echo "<script>window.open('shop_products.php','_self')</script>";
}
?>
</div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-4 footer-grid">
<h3>Menu</h3>
<ul class="list1">
<li>Home</li>
<li>Shop Products</li>
<li>My Account</li>
<li>Contact Us</li>
<li>Login</li>
</ul>
</div>
<div class="col-md-4 footer-grid">
<h3>Your Account</h3>
<ul class="list1">
<li>My Orders</li>
<li>Edit Account</li>
<li>Change Password</li>
<li>Delete Account</li>
<li>My Cart</li>
</ul>
</div>
<div class="col-md-4 footer-grid">
<h3>About Us</h3>
<p class="footer_desc">Zeus is a pharmacy focused on providing patients with what they need and deserve - exceptional pharmacy care. It is our responsibility and passion to care for your medication needs.</p>
<p class="f_text"><span class="fa fa-phone" aria-hidden="true"></span> Phone: +081 123 45 67</p>
<p class="email"><span class="fa fa-envelope" aria-hidden="true"></span> Email: <span>info#zeuspharmacy.com</span></p>
</div>
<div class="clearfix"> </div>
</div>
</div>
</div>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-12 footer-grid-bottom">
<div class="copyrights">
<p>© 2017 Zeus Pharmacy. Made with <span class="fa fa-heart" aria-hidden="true"></span> by Dilum Tharaka</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
order table structure image
payment table structure image
Above are the table structures I'm using. Thanks in advance

Timer and Navigation in online aptitude test

I am a novice in php web app dev.I am designing an online aptitude test. But i met some problem that i couldnt proceed further. This are
The timer restart itself when i click on the navigation for next question
When a question is not answered and the next button is clicked, an eror pops out.
I have poor knowlege of ajax and jquery but belive they can be usedful. Help me in what ever way please to achieve my goal.
below are my codes:
//test.php
<?php
session_start();
// th value of q is given as 1 from the start quiz button of the users home page
if (isset($_GET['q'])) {
$number = (int)$_GET['q'];
}else{
header('Location : index.php');
}
if(!isset($_SESSION['user_session']))
{
header("Location: ../login.html");
}
//connection to the db
include_once '../dbconfig.php';
$stmt = $db_con->prepare("SELECT * FROM tbl_admin WHERE aid=:uid");
$stmt->execute(array(":uid"=>$_SESSION['user_session']));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$qr = $db_con->prepare("SELECT * FROM questions ");
$qr->execute();
$count = $qr->rowCount();
$qrow=$qr->fetch(PDO::FETCH_ASSOC);
$qst = $db_con->prepare("SELECT * FROM questions where quesNo='$number' ");
$qst->execute();
$qstrow=$qst->fetch(PDO::FETCH_ASSOC);
?>
<body>
<header id="header">
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><div id="hms">00:05:00</div></a>
</div>
<div id="navbar" class="navbar-collapse collapse">
</header>
<div class="item active">
<?php
//Code to process score(saved is session variable) and move to the next question
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$ans=$_POST['ans'];
$number=$_POST['number'];
$next = $number+1;
if (!isset($_SESSION['score'])){
$_SESSION['score'] = '0';
}
$qrs = $db_con->prepare("SELECT * FROM questions ");
$qrs->execute();
$counts = $qrs->rowCount();
$sqlans= "SELECT * FROM answers where quesNo='$number' and right_ans='1'";
foreach ($db_con->query($sqlans) as $rowsans) {
if($ans==$rowsans['ans_id']){
$_SESSION['score']++;
}
if($number==$count){
header('location:final.php');
exit();
}else{
header('location:test.php?q='.$next);
}
}
}
?>
<div class="containerx" style="height:530px;">
<div class="image" style="width:100%">
<div class="main">
<hl> Question <?php echo $number ?> of <?php echo $count; ?></hl>
<div class="test">
<form method="post" action="">
<table>
<tr>
<td coLspan=”2”>
<h3>Que <?php echo $qstrow['quesNo']; ?>: <?php echo $qstrow['ques']; ?></h3>
</td>
</tr>
<?php
$sqla= "SELECT * FROM answers where quesNo='$number'";
foreach ($db_con->query($sqla) as $rowsa) {
?>
<tr>
<td>
<input type="radio" name="ans" value=" <?php echo $rowsa['ans_id']; ?>"/> <?php echo $rowsa['ans']; ?>
</td>
</tr>
<?php } ?>
<tr>
<td>
<input type="submit" id="btn_next" name="submit" value="Next Question"/>
<input type="hidden" name="number" value="<?php echo $number ?>"/>
</td>
</tr>
</table>
<!--<div class="caption page-carousel pull-left">-->
</div>
<div class="site-full-width darkbluecolor">
<div class="container">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function count(){
var startTime = document.getElementById('hms').innerHTML;
var pieces= startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
console.log( time.setMinutes(pieces[1]));
time.setSeconds(pieces[2]);
console.log( time.setMinutes(pieces[1]));
var timedif = new Date(time.valueOf() - 1000);
var newTime=timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newTime;
if(newTime==="00:00:00"){
clearTimeout(time_out);
$('#btn_next').css('display',' none');
alert("Sorry Your time is over");
}
time_out= setTimeout(count,1000);
}
count();
});
</script>

header location not working on online godaddy hosting but working on local host

the header location work perfect on local host but on godaddy hosting online not work how can i solve this problem this my login code
ob_start();
include("includes/connect.php");
if(isset($_POST['login'])){
$username=strip_tags(mysqli_escape_string($conn,$_POST["txt_username"]));
$pass=strip_tags(mysqli_escape_string($conn,$_POST["txt_pass"]));
if($username=="" || $pass=="")
{
echo"Enter Username And Password.";
}else{
$sql=mysqli_query($conn,"select* from tbl_user where db_username='$username' and db_pass='$pass'")or die(mysqli_error($conn));
$count = mysqli_num_rows($sql);
$res=mysqli_fetch_array($sql);
if($count==1){
$query=mysqli_query($conn,"update tbl_user set db_isonline='1' where db_username='$username'")or die(mysqli_error($conn));
$user=$res['db_username'];
$_SESSION["username"]=$res['db_username'];
$_SESSION["level"]=$res['db_level'];
$_SESSION['LAST_ACTIVITY'] = time();
header("location:main.php");exit();
}else{ echo"Username Or Password Incorrect";}
}
}
ob_end_flush();
main page code
ob_start();
include("includes/connect.php");
if(isset($_SESSION['username'])){
$username=$_SESSION['username'];echo $_SESSION["username"];
$query=mysqli_query($conn,"select* from tbl_user where db_username='$username'")or die(mysqli_error($conn));
$res=mysqli_fetch_array($query);
$fname=$res['db_fname'];
$lname=$res['db_lname'];
}else{
if(!isset($_SESSION['username']) || $_SESSION['username']=="" ){
header("location:index.php");}}
ob_end_flush();
and i have some php code in my header that is
ob_start();
session_start();
if(empty($_SESSION['username'])) {
echo'
<nav class="navbar navbar-default" role = "navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="main.php"><img src="img/t-square-logo-Final.png" alt="the professionals" width="200px" style="float:left;margin-top:41px;" /></a>
</div>
<div class = "collapse navbar-collapse" id = "example-navbar-collapse">
</div>
</div></div>
</nav>
</div>';
}
else{
if($_SESSION['level']==0){
echo'
<nav class="navbar navbar-default" role = "navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type = "button" class = "navbar-toggle"
data-toggle = "collapse" data-target = "#example-navbar-collapse">
<span class = "sr-only">Toggle navigation</span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
<span class = "icon-bar"></span>
</button>
<a class="navbar-brand" href="main.php"><img src="img/t-square-logo-Final.png" alt="the professionals" width="200px" style="float:left;margin-top:41px;" /></a>
</div>
<div class = "collapse navbar-collapse" id = "example-navbar-collapse">
<ul class="nav navbar-nav">
<li ';?><?php if ($page_name=="search.php")
echo"class=\"active\""; ?><?php echo'>Order</li>
<li>Task</li>
<li>Logout</li>
</ul>
</div>
</div></div>
</nav>
</div>';}ob_end_flush();
i use this to print the error
error_reporting(E_ALL);
and this is the error i have but i don't know how to solve it
Warning: Cannot modify header information - headers already sent by (output started at /home/mhmd2991/public_html/index.php:2) in /home/mhmd2991/public_html/index.php on line 39

Custom php Login Form: using a modal

I am trying to get my login php working. I can't find what's wrong. I've had it working before, but it stopped all of the sudden. I am using bootstrap also, but I don't think that would cause any problems. Everything between the php and the form seems to match up. I am using a javascript and css modal for the login form, but I don't think that would effect it either.
PHP:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['usr_id'])) {
echo "Successfully Logged In!";
//header("Location: index.php");
}
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email . "' and password = '" . md5($password) . "'");
?>
<!--<script>
alert("<?php echo 'Result is: '.$result; ?>");
</script> -->
<?php
$row = mysqli_fetch_array($result);
echo $row;
if ($row != NULL) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
// header("Location: index.php");
} else {
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
Here is my login modal with the form:
<!-- The Modal -->
<div id="login" class="modal">
<!-- Modal content -->
<div class='js-fade fade-in is-paused'>
<div class="modal-content">
<span class="close" data-dismiss="modal">x</span>
<form role="form" action="index.php" method="post" name="loginform">
<fieldset>
<legend>Login</legend>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" id="email" placeholder="Your Email" required class="form-control" />
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" id="password" placeholder="Your Password" required class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" value="login" class="btn btn-info login" role="button" />
</div>
</fieldset>
<div class="signupbtn">
<li>Don't have an account? Sign Up here.</li>
</div>
</form>
</div>
</div>
</div>
Navbar:
<!-- Nav Bar -->
<nav class="navbar navbar-default navbar-fixed-top navbar-left">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand brand" href="#" style="font-family: Warnes">Unleasht</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="navbarli">HOME</li>
<li class="navbarli">ABOUT</li>
<li class="navbarli">MUSIC</li>
<li class="navbarli">CONTACT</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<?php
function loggedIn(){
if(isset($_SESSION['usr_id']))
{ echo '<li class="dropdown">
'. $_SESSION['user'] .'<span class="caret"></span>
<ul class="dropdown-menu">
<li>'. $_SESSION['usr_name'] .'</li>
<li>Account</li>
<li role="separator" class="divider"></li>
<li><a action="login/logout.php">Logout</a></li>
</ul>
</li>';
}else{
unset($_SESSION['usr_id']);
echo '<li><span class="glyphicon glyphicon-log-in navbarli"></span> Login</li>';
}
}
loggedIn();
?>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
What am I doing wrong?
You can not set $_SESSION['usr_id'] after you have sent any header, try following code:
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['usr_id'])) {
echo "Successfully Logged In!";
}elseif (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email . "' and password = '" . md5($password) . "'");
if (mysqli_num_rows($result)==1) {
$row = mysqli_fetch_array($result);
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
echo "OK fine";
} else {
echo "Incorrect Email or Password!!!";
}
}
?>

Categories