SQL Insert executes twice, php - php

Couldn't find a straight answer to this. My custom wordpress php code seems to be executed twice when I click on the submit once. When clicked, the codes adds two cities with the same name. As you can see, I tried to aviod this by checking for duplicates, but it ignores it... I tried moving the html to a function, but not help there either. Now my code looks weird and still no solution. Any new ideas?
<?php get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php
// Start the loop.
while ( have_posts() ) : the_post();
// Include the page content template.
get_template_part( 'template-parts/content', 'page' );
if ( comments_open() || get_comments_number() ) {
comments_template();
}
// End of the loop.
endwhile;
?>
</main><!-- .site-main -->
<?php
function showForm() {
echo "<form name='submit' method='post'>";
echo "<select name='countriesSelect'>
<option value='-1'>Choose...</option>";
$conn = new mysqli('localhost','a','b','c');
$query = "SELECT id,country_name FROM countries";
$result = $conn->query($query);
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row['id'] . "'>" . $row['country_name'] . "</option>";
}
$conn->close();
echo "</select><br /><br />
Now choose a new city: <input type='text' name='cityname' maxlength='30' size='30' value='' style='width: 300px;' /><br /><br />
That is it: <br />
<input type='submit' value='Add new city' /><br /><br />
</form>";
return;
}
if (!empty($_POST['cityname']) && !empty($_POST['countriesSelect'])) {
$cityname = $_POST['cityname'];
$countriesSelect = $_POST['countriesSelect'];
// make sure city doesn't exist - also because for some unknown reason this script is called twice =/
$db = new mysqli('localhost','a','b','c');
$query = "SELECT city_name FROM cities WHERE city_name='$cityname'";
$result = $db->query($query);
$row = $result->fetch_assoc();
if (empty($row['city_name'])) {
// add new city
$query = "INSERT INTO cities (country_id, city_name, amount_raised_usd) VALUES ($countriesSelect, '$cityname', 0)";
$result = $db->query($query);
if ($db->query($query) === TRUE) {
echo "<div style='color: green;'>New city added successfully. Add another?";
} else {
echo "<div style='color: red;'>Error: " . $query . " :: " . $db->error;
}
echo '</div><br /><br />';
}
$db->close();
showForm();
} else {
showForm();
}
?>
<?php get_sidebar( 'content-bottom' ); ?>
</div><!-- .content-area -->
<?php get_footer(); ?>

Do you see this
$result = $db->query($query);
And the next line:
if ($db->query($query) === TRUE) {
This means that you run your query twice. Remove one of the $db->query, e.g.:
$result = $db->query($query);
if ($result === TRUE) { /* do stuff */

you execute the query twice:
$result = $db->query($query);
if ($db->query($query) === TRUE) {
should be:
$result = $db->query($query);
if ($result === TRUE) {

Related

Repeated Record in php and mysql

I am trieng to list item form the database, however, the result comes out in two. 2 result is displayed for each record. currently i only have one record in the database but when i display them on the screen it is repaeted. i do not know why this is happening, i have tried to palce a counter and see how many times the loop goes on and the result is always once. however the result is displayed two times.
the code as follows:
<section class="container">
<div class="row">
<?php
if($bidCollection->selectBidsByStatusAndAppId(BidAccount::OPEN_NEW, $id)){
foreach($bidCollection->getBids() as $bid){
$banker->find($bid->getCustomerId());
$counter=0;
?>
<div class='col-xs-12 bg-more-light-gray bidlist'>
<div class="col-xs-12 col-sm-1 col-md-1">
<?php
if(!$uploader->findProfilePicture($banker->data()->_customer_id)){
echo "<img src='image/holder.png ' width='50' height='50' class='img-responsive' />";
}else{
echo "<img src='upload/proPicture/".$uploader->data()->pictureUrl."' width='50' height='50' class='img-responsive'/>";
}
?>
</div>
<div class="col-xs-12 col-sm-8 col-md-8">
<?php
echo '<h2>Agent name :'.$validate->cleanInput($banker->data()->officer_name).'</h2>';
echo '<h3>Institute name : '.$validate->cleanInput($banker->data()->bank_name).' '.++$counter.'</h3>';
if($bid->getApplicationOwnerId() === $customer->data()->_customer_id){
echo "<p>CheckBook: ";
if($bid->getRequestCheckBook()){echo "Yes";}else{echo "No";}
echo "</p>";
echo"<p> Minimum Deposit: AED ".$bid->getMinDeposit()."</p>";
echo"<p> Direct Debit Card: ";
if($bid->getRequestCreditCard()){echo "Yes";}else{echo "No";}
echo "</p>";
echo"<p> Other Fees / Arrangement Fees: AED ".$bid->getFees(). "</p>";
echo"<p> Account Will be ready in: ".$bid->getSetupTime() ."</p>";
}
?>
</div>
<div class="col-xs-12 col-sm-2 col-md-2">
<?php
$datetime = new DateTime($bid->getDatePosted());
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
echo '<h4> Date: '.$date.'<br/>Time: '.$time.'</h4>';
echo"<form method='POST' action='viewBanker.php'>";
echo "<input type='hidden' name='banker' value='".$bid->getCustomerId()."'>";
echo "<input type='submit' class ='btn btn-default' name='submit' value='View Profile'>";
echo "</form>";
echo'<br/>';
if($bid->getApplicationOwnerId() === $customer->data()->_customer_id){
echo"<form method='post' action='acceptAccountBid.php'>";
echo "<input type='hidden' value='".$bid->getCustomerId()."' name ='bankerId'/>";
echo "<input type='hidden' value='".$id."' name ='appid'/>";
echo "<input type='hidden' value='".$bid->getApplicationOwnerId()."' name='ownerId'>";
echo "<input class='btn btn-default' type='submit' value='Accept Offer' name='submit'>";
echo"</form>";
}
?>
</div>
</div>
<?php
}
}
?>
The Methods that returns the the values is as follows:
public function selectBidsByStatusAndAppId($status, $appid)
{
$sql = "SELECT * FROM accountBid WHERE application_id = :appId AND status = :st";
try {
$sth = $this->_db->getConnection()->prepare($sql);
$sth->bindValue(':appId', $appid);
$sth->bindValue(':st', $status);
$sth->execute();
} catch (Exception $e) {
$this->setAlert('danger', 'Information Presentation Error: ' . $e->getMessage());
}
foreach ( $sth->fetchAll(PDO::FETCH_ASSOC) as $data) {
$this->addBid($data);
}
return true;
}
public function addBid($data = null)
{
$bid = new BidAccount($data);
$this->bids[] = $bid;
}
public function getBids()
{
return $this->bids;
}
first of all, I want to thank my mates who tried to help me earlier. the problem was I had another function which I forgot to post it here bidExist()
public function bidExist( $appId , $id){
$sql = "SELECT * FROM accountBid WHERE application_id = :appId AND _customer_id = :id";
try {
$sth = $this->_db->getConnection()->prepare($sql);
$sth->bindValue(':appId', $appId);
$sth->bindValue(':id', $id);
$sth->execute();
} catch (Exception $e) {
$this->setAlert('danger', 'Information Presentation Error: ' . $e->getMessage());
}
foreach ( $sth->fetchAll(PDO::FETCH_ASSOC) as $data) {
$this->addBid($data);
}
return $sth->rowCount();
}
The function above looped through the collection to check and see if the object exists before this and if it is then you can not add anymore bid, however, i forgot to remove the addBid() function on this method and that cause the object to be added twice to the collection. This took me the whole night to figure out. but I thank everyone who tried to support and assist.

I am trying to print all the database users in a Unordered list in PHP. But it is not working

<ul>
<?php
$sql = "SELECT first_name, last_name FROM loginsystem";
if ($result = mysqli_query($connection, $sql)) {
if ($total_rows = mysqli_num_rows($result)) {
while ( $row = mysqli_fetch_assoc($result) ) : ?>
<li>
<?php $row['first_name'] . " " . $row['last_name']; ?>
</li>
<?php
endwhile;
mysqli_free_result($result);
}
}
?>
</ul>
The above code is not working. Please help to solve this issue. Please help me
You are not actually outputing anything in your while loop, you need only add an echo to this line
<?php echo $row['first_name'] . " " . $row['last_name']; ?>

PHP & MySQL - Update Query not updating database

I'm making a personal website and I just wanted it to be a bit easier for me to add/edit my posts without manually going into phpmyadmin.
When I go to the edit_post.php page and press update I get an "=" sign next to the pid eg.(foo.php?pid=3), and if i let it redirect to the blog page it doesn't update it.
Blog page
<?php
session_start();
include_once("../IncBlog/db.php");
?>
<?php include "../Includes/navHead.php"; ?>
<title>Adam Brickhill - Life Journal </title>
</head>
<body>
<div class="box">
<div class="header">
<nav class="nav"><p class="title"><a class="postLink" href="../IncBlog/post.php">- Lone Tree -</a></p></nav>
</div>
<!-- JOURNAL !-->
<?php
require_once("../nbbc/nbbc.php");
$bbcode = new BBCode;
$sql = "SELECT * FROM posts ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die(mysqli_error());
$posts = "";
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$title = $row['title'];
$img = $row['img'];
$content = $row['content'];
$date = $row['date'];
$admin = "<div><a href='../IncBlog/del_post.php?pid$id'>Delete</a> <div><a href='../IncBlog/edit_post.php?pid$id'>Edit</a>";
$output = $bbcode->Parse($content);
ob_start();
include('../IncBlog/blogSkel.php');
$posts .= ob_get_contents();
ob_end_clean();
}
echo $posts;
}
else {
echo "There are no posts to display";
}
?>
<div class="journal">
<div class="catagories">
</div>
<!-- Date !-->
<!-- Picture !-->
<!-- Description !-->
</div>
<?php include "../Includes/navFooter.php"; ?>
<!-- SCRIPTS !-->
<?php include "../Includes/navScriptImport.php"; ?>
</div>
</body>
</html>
Edit Page
<?php
session_start();
include_once("db.php");
if (!isset($_SESSION['username'])) {
header("Location: login.php");
return;
}
$pid = $_SERVER['REQUEST_URI'];
$pid = trim($pid, "/IncBlog/edit_post.php?pid");
$pid = strip_tags($pid);
$pid = stripslashes($pid);
$pid = mysqli_real_escape_string($db, $pid);
//echo "$pid";
if ($pid == "") {
header("Location: ../Nav/life.php");
}
if (isset($_POST['update'])) {
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$img = strip_tags($_POST['image']);
$title = mysqli_real_escape_string($db, $title);
$content = mysqli_real_escape_string($db, $content);
$img = mysqli_real_escape_string($db, $img);
$date = date("l jS \of F Y h:i:s A");
$sql = "UPDATE posts SET title='$title', content='$content', img='$img', date='$date' WHERE id=$pid";
if ($title == "" || $content == "") {
echo "The database is hungry you can't feed it nothing!";
return;
}
mysqli_query($db, $sql);
header("Location: ../Nav/life.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Blog - Post</title>
</head>
<body>
<?php
$sql_get = "SELECT * FROM posts WHERE id=$pid LIMIT 1";
$res = mysqli_query($db, $sql_get);
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_assoc($res)) {
$title = $row['title'];
$content = $row['content'];
$img = $row['image'];
echo "<form action='edit_post.php?pid=$pid' method='post' enctype='multipart/form-data'>";
echo " <input placeholder='Title' type='text' name='title' value='$title' autofocus size='48'><br /><br />";
echo " <input placeholder='Image' type='text' name='image' value='$img' autofocus size='48'><br /><br />";
echo " <textarea placeholder='Content' name='content' rows='40' cols='40'>$content</textarea><br />";
}
}
?>
<input type="submit" name="update" value="Update">
</form>
</body>
</html>
You have to set the columns and set the values for the columns.
UPDATE posts SET ( title, content, img, date ) VALUES ($title, $content, $img, $date) WHERE id = $pid;
$date = date("l jS \of F Y h:i:s A");
use instead of above line
$date = date('Y-m-d H:i:s', strtotime());
$sql = 'UPDATE posts SET title='".$title."', content='".$content."', img='".$img."', date='".$date."' WHERE id='".$pid."'";
Ok so I figured it out, very small programmers blindness but hey we all get it.
Line 66 echo "<form action='edit_post.php?pid$pid' method='post' enctype='multipart/form-data'>";
Where it says "?pid$pid" I just needed to remove the "=" that i had there.

PHP - Foreach via Certain active Sessions

I'm currently working on a super simple Online shop idea with a shopping cart. At the end i want to print out a table with the products you ordered. Currently using a foreach but i have no idea how to solve this. I tried to use sessions as a way to give the loop an idea how many different products are ordered. But it seems like the $_SESSION way will take all the current active sessions. And using a simple variable f.e. $piano will make it print 2 rows ( using 2 piano's in my shop, tried to solve it with a if (session active) $piano1 = active. But it seems the foreach statement doesn't give a whoop about that and will print 2 rows anyways.
Sorry for the long block of text. Here's my page. Again apologies. I just started php.
Variable names are dutch but that shouldn't really matter for you guys i think.
Starting from line 103.
Thanks in advance!
<div class="logincontainer"><!-- Php Session Script Actief? -->
<?php
session_start();
if(isset($_SESSION['naam'])) :
echo "<div class='content_login'>";
echo "Hallo " . $_SESSION['naam'] . ". Welkom bij de Pianoshop.</br></br>";?>
<form method='post' action='uitlog.php'>
<input type='submit' name='loguit' Value='Loguit!'></form><br />
<form action='winkelmand.php' class="left">
<input type='image' src='images/winkelwagen-knop.png'/>
</form><br />
<form method='post' name='emptycart' action='emptycart.php' class="right">
<input type="submit" id="submitpic" name="leegwinkelmand" value="">
<?php
if(isset($_SESSION['winkelmand'])) {
echo $_SESSION['aantalproducten'] . " Item(s) - €" . $_SESSION['totaalprijs'] . ",-";
} else {
echo "Jouw winkelwagen is leeg.";
}?>
</form>
</div>
<?php else :?>
<div class='content_login'>
<form method='post' action='checklogin.php'>
<p><input type='text' name='gebruikersnaam' required='required' value='' placeholder='Gebruikersnaam'></p>
<p><input type='password' name='password' required='required' value='' placeholder='Wachtwoord'></p>
<font color="red"><p class='submit'>
<input type='submit' name='login' value='Login'>
<?php if(isset($_SESSION['logged_in'])) :?>
Verkeerd wachtwoord.
<?php session_destroy();
endif; ?>
</p></font>
<p>Nog niet geregistreerd? Doe dat hier!.</p>
</form>
</div>
<?php endif; ?></div>
<div id="site">
<div id="menubar">
<div id="logo">
<img src="images/pianotoetsen.png" >
</div>
<div id="menu_items">
<ul id="menu">
<li>Home</li>
<li>Toetsinstrumenten</li>
<li>Jouw account</li>
<li class="current">Winkelmand</li>
<li>Contact</li>
</ul>
</div></div>
<div id="site_content">
<div class="sidebar_container">
<div class="sidebar">
<h2>Sale!</h2>
<div id="thumbnail"><img src="images/piano1.jpg"></div>
<p>Yamaha CLP-575 voor maar €2599,- !</p>
<div id="thumbnail"><img src="images/piano2.jpg"></div>
<p>Ritmuller 120SL €4999,- !</p>
</div>
<div class="sidebar">
<h2>Laatste Updates</h2>
<h3>Juni 2015</h3>
<p>Site in constructie.</p>
</div>
<div class="sidebar">
<h3>Wij zijn op Facebook</h3>
<p>Klik hier.</p>
</div>
</div>
<div id="content">
<div id="wallpaperbanner">
<img src="images/banner.jpg">
</div>
<div class="content_item">
<h1>Winkelmand</h1>
<?php
$user = 'root';
$pass = '';
$db = 'online shop';
$conn = mysql_connect('localhost', $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(isset($_SESSION['winkelmand'])) {
echo "Deze producten staan in je winkelwagen</br></br>";
if(isset($_SESSION['totaalprijs2']) == 0) {
// Do nothing?
} else {
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='2'");
$productgegevens = mysql_fetch_row($query);
$piano["piano2"] = "ritmuller";
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
if(isset($_SESSION['totaalprijs1']))
{
mysql_select_db($db);
$query = mysql_query("SELECT * FROM product WHERE productnummer='1'");
$productgegevens = mysql_fetch_row($query);
$piano["piano1"] = "yamaha";
$pianoarray[4] = $_SESSION['aantal_prod1'];
$pianoarray[1] = $productgegevens['1'];
$pianoarray[2] = $productgegevens['2'];
$pianoarray[3] = $productgegevens['4'];
$pianoarray[5] = $productgegevens['3'];
$pianoarray[4] = $_SESSION['aantal_prod2'];
}
echo "<br />
<table width='80%' >
<thead>
<tr><th>Productnaam</th><th>Merk</th>
<th>Voorraad</th><th>Aantal</th><th>Prijs</th>
</tr>
</thead>
<tbody>";
foreach($piano as $key => $value) {
echo $key . "</br>" . $value . "<br />";
$row = "<tr>";
for ($x=1; $x<=sizeof($pianoarray); $x++){
$row = $row . "<td>" . $pianoarray[$x] . "</td>";
}
$row = $row . "</tr>";
echo $row;
}
echo "<tr><td></td><td></td><td></td><td></td><td>" . '€' . $_SESSION['totaalprijs'] . ',-' . "</td></tr></tbody></table>";
}
else {
echo "Jouw winkelwagen is leeg. <br />" . "Klik <a href='toetsinstrumenten.php'>Hier</a> om wat items toe te voegen.";
}?>
</div>
</div>
</div>
</div>
Create an array variable in the $_SESSION array and do a foreach loop on that
$_SESSION['cart']['piano1'] = 'piano1';
$_SESSION['cart']['piano2'] = 'piano2';
$cart = $_SESSION['cart'];
foreach ($cart as $key => $item) {
//do something with $item or $key
}

Next and previous links and ID displayed in the URL for sharing

I have a database with a few images already set, I would like to have the url display an ID from each query as the user hits next. The user should be able to share the URL and paste it into their browser, the url should pull that unique ID from the query. The issue i am having is every time i paste a url, I get a random image and not the image that is in the ID. I'm at a loss here and im not sure what to do :( here's the code I have so far.
<?php
if (isset($_GET['id'])) {
include("PHP/db.php");
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
if($_GET['next4']) {
echo 'HELLO THIS IS THE NEXT IF METHOD';
include("PHP/db.php");
$query = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $ID ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
Try this:
<?php
include("PHP/db.php");
$query2 = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result2 = mysqli_query($dbc, $query2);
$rand_row = mysqli_fetch_array($result2);
$rand_id = $rand_row ['ID'];
if (!isset($_GET['id'])) {
$_GET['id'] = $rand_id;
}
if (isset($_GET['id'])) {
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $rand_id; ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
I changed:
-link to next is now id=rand
-changed your code to give me a "rand ID" and its already defined on the href of the page you load
It will go inside condition (next == true).
Make sure that your variables are initialized before use.

Categories