this might be a really simple solution but I really can't figure it out. if i insert into my database I have to press the insert button twice for it to work.. My guess is that it has to do with my using of 2 forms in one file or just because I did it all in one file. please help me.
thanks
code:
<?php
/*require "link.php";*/
?>
<html>
<head>
<!--<link rel="stylesheet" type="text/css" href="css.css">--> <!-- verwijzing naar je css -->
<!--<script type="text/javascript" src="js.js"></script>-->
</head>
<header>
</header>
<article>
<div id="cards">
<?php
$host = "localhost";
$user = "root";
$pwd = "";
$db_name = "flashcards";
$link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");
$array = array();
$IDarray = array();
ini_set('display_errors', 1);
error_reporting(E_ALL);
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{
echo "<tr id='".$rows['ID']."'><td>".$rows['Question']."</td><td><input type='text' name='Answer[]' id='V".$rows['ID']."'></input></td></tr>";
$array[] = $rows["Answer"];
$IDarray[] = $rows["ID"];
}
echo "</table><input type='submit' name='submit'></input></form>";
$i = 0;
$count = sizeof($IDarray);
if(!empty($_POST['Answer']))
{
foreach($_POST['Answer'] as $answer)
{
if (isset($_POST['Answer'])) {
if ($answer == $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='green'; document.getElementById('V".$IDarray[$i]."').value='".$array[$i]."'</script>";
}
elseif ($answer !== $array[$i])
{
echo "<script>document.getElementById('".$IDarray[$i]."').style.background='red'; document.getElementById('V".$IDarray[$i]."').value='".$answer."'</script>";
$count = $count-1;
}
$i ++;
}
}echo $count." van de ".sizeof($IDarray)." goed";
if ($count == sizeof($IDarray))
{
header('Location: http://localhost:1336/php3/');
}
}
echo "</br></br>insert";
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
echo "<tr><td>vraag</td><td><input type='text' name='vraag'></input></td><td>antwoord</td><td><input type='text' name='antwoord'></input></td></tr>";
echo "</table><input type='submit' name='submitinsert' value='insert'></input></form>";
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
?>
</div>
</article>
<footer>
</footer>
</html>
The problem is you're processing the form submission in the same script as the one that generates the form. Couple that to the fact that you firsT query the DB, generate a form with what you've already stored, and then add whatever data the user may have posted, you'll never see the data you've added show up the first time 'round you submit the form.
Either move the insert queries to the top (before generating the form), or separate concerns
Let me show you what I mean:
//don't OR DIE
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or die(mysqli_error($link));
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
while ($rows = mysqli_fetch_assoc($sql))
{//build form here
}
/*
CODE HERE
*/
if ($_POST['vraag'] != "") {
//insert here, after form is generated
}
So the data you query cannot, yet, contain the submitted form data.
There are some other issues with the code, though, like or die: don't do that. Be consistent with your coding style (allman brackets + K&R in the same script is messy). Properly indent your code and this:
if ($_POST['vraag'] != "") {
}
should be:
if (isset($_POST['vraag'])) {
}
You're comparing a key of an array that may not exist to an empty string, whereas you should check if that array key exists. Use isset.
I could go on a bit, but I'll leave it at that for now. Just one more thing: again -> separrate concerns! The presentation layer (the output: HTML and such) should not contain DB connection stuff. That should be done elsewhere.
Process your form either asynchronously (as whatever is submitted gets added to the table that is already there) using AJAX, or at least, use a separate script. Having 1 script doing all the work will soon leave you crying over a mess of spaghetti code
Its not submitting twice, actually its not loading the data after insertion,
Try adding
if ($_POST['vraag'] != "") {
$vraag = $_POST['vraag'];
$antwoord = $_POST['antwoord'];
echo "are you sure?";
mysqli_query($link, "INSERT INTO questions (Question, Answer) VALUES (".$vraag.",".$antwoord.");") or die(mysqli_error($link));
}
before
$sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC ") or
die(mysqli_error($link));
this will select your records after the current record is saved.
Related
I have stayed up two nights and I haven't been able to fix this. I am new to the site as well as in PHP please forgive my inexperience. The idea is that when a user selects several courses it should be sent to the database and stored in separate rows. what happens now is that it stores only the first value twice in the database. thanks.
code:
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$user_id=$_SESSION['user_id'];
?>
<h2>Register</h2>
<?php
if(isset($_GET['success']) && empty($_GET['success'])){
echo 'You have successfully registered!';
}
else{
if(empty($_POST)===false){
$course[]=$_POST['course_code'];
$user_id= $user_data['user_id'];
$username=$user_data['username'];
foreach($course as $c){
$data= '\''.implode('\',\'',$c).'\'';
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUE ('$user_id','$username', $data)");
header('location:courses.php?success');
exit();
}
}
?>
<form action="" method="post">
<?php
$sql = "SELECT * FROM course";
$result = mysql_query($sql)or die(mysql_error());
echo "<table>";
echo "<tr><th>COURSE CODE</th><th>COURSE TITLE</th><th>UNIT</th><th>SEMESTER</th><th>LEVEL</th></tr>";
while($row = mysql_fetch_array($result)){
$course_code = $row['course_code'];
$course_title = $row['course_title'];
$course_unit = $row['course_unit'];
$semester = $row['semester'];
$level = $row['level'];
echo "<tr><td style='width: 100px;'>".$course_code."</td><td style='width: 600px;'>".$course_title."</td><td>".$course_unit."</td><td>".$semester."</td><td>".$level."</td><td><input type=\"checkbox\" name=\"course_code[]\" value=".$course_code."></td></tr>";
} // End our while loop
echo "</table>";
?>
<input type="submit" value="Register">
</form>
<?php
}
include 'includes/overall/footer.php';
?>
Your code is dangerous. It is not resistant for sql injection. You should stop using mysql_ functions and switch to mysqli or PDO.
But just to fix the bug now you can change your code in this part:
foreach($course as $c){
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`)
VALUES ('$user_id','$username', $c)");
}
header('location:courses.php?success');
exit();
redirection inside loop stopped the process so it did only once. for good practice do not put sql query inside loop it makes slow process.
$values = '';
foreach($course as $c){
$values .= "('$user_id','$username', '$c'), ";
}
$values = rtrim($values, ',');
mysql_query("INSERT INTO `lenroc_ssims`.`registercourses`(`user_id`, `username`, `course_code`) VALUES {$values}");
header('location:courses.php?success');
exit();
if you don't agree, why you don't write some comment?
This is my code so far:
require_once 'functions.php';
// makes the connection to the server to get the state button names
$query = "SELECT state FROM state";
$result = $connection->query($query);
if ($result === false) {
// error mssg
echo "<p>Query fout.</p>";
}
// button of the state gets the buttons of the city
if (isset($_POST['state'])) $state = $_POST['state']; {
query = "SELECT city FROM city='$cityid'";
$result = $connection->query($query);
} if ($result === false) {
// geef nette foutmelding
echo "<p>Query fout.</p>";
}
<?php
//gives the result to Submit html
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."'>";
}
$result->free();
?>
</for
I would like to have a form submit button that gives a variable to PHP, depending on that variable, other buttons are created in the same form. So you can select a country and than you can select the cities in that country. I have the first button up and running. I thought I could just use the same submit button with the same variables. Because php would just rewrite the variables if there is a new input. But I think its not that simple, I don't know how to Google this question or that it is even something I should do with PHP instead of JavaScript/jQuery and just let the buttons hide and display and only use the last one to give an input with PHP.
you need to do the query result separately, so there should be two while statements
not the best way but here is one way i would do it:
require_once 'functions.php';
$query = "SELECT state FROM state";
if($query->num_rows > 0){
while($row= $result->fetch_assoc()) {
echo "<input type ='submit' name='provincie' value='".$row['provincie']."' onclick="sendVal(this.value)" >";
}
}
<script type="text/javascript">
function sendVal(item) {
document.cookie="city=" + item + ";";
location.reload();
}
</script>
<?php
if(!is_null($_COOKIE['city'])){
$retrievedcities= "SELECT city FROM city WHERE city ='".$_COOKIE['city']."'";
$con->query($retrievedcities);
while ($row = $result->fetch_assoc()) {
echo "<input type ='submit' name='citybut' value='".$row['city']."'>";
}
unset($_COOKIE['city']);
}
?>
I'm just learning PHP and MySQL, so I'm guessing my error is really obvious.
I have a DB Table called inventory and I'm trying to pull up information on the car named Mustang. That is the name of the car under the Make column.
The problem I'm having is that my first echo statement is not ending with what should be the closing " and the following ;. It is echo'ing everything that follows it in the code, down to the ?> at the end of the file.
Here is the code itself. Note this is just a database I threw together in 10 minutes in phpmyadmin and not anything official.
<!DOCTYPE html>
<html>
<head>
<title>Realistic Autos Inventory</title>
<script>
<?php
function GetInventory($CarName)
{
$user="Uhrmacher";
$host="localhost";
$password="";
$dbname="realistic autos";
$cxn= mysqli_connect($host, $user, $password, $dbname) or die("Failure to Communicate!");
$query = "SELECT * FROM inventory WHERE Make='$CarName'";
$result = mysqli_query($cxn, $query) or die ("Failure to Query!");
$index=1;
while($row=mysqli_fetch_query($result))
{
foreach($row as $colname => $value)
{
$array_multi[$index][$colname]=$value;
}
$index++;
}
return $array_multi;
}
?>
</script>
</head>
<body>
<?php
$CarName = "Mustang";
$CarInfo = GetInventory($CarName);
echo "<h1>{$type}s</h1>\n";
echo "<table cellspacing='15'>\n";
echo "<tr><td colspan='4'><hr /></td></tr>\n";
for ($i=1; $i<=sizeof($CarInfo); $i++)
{
$f_price = number_format($CarInfo[$i]['Price'], 2);
echo "<tr>\n
<td>$i.</td>\n
<td>{$CarInfo[$i]['StockNumber']}</td>\n
<td>{$CarInfo[$i]['Year']}</td>\n
<td>{$CarInfo[$i]['Make']}</td>\n
<td>{$CarInfo[$i]['Model']}</td>\n
<td>{$CarInfo[$i]['Package']}</td>\n
<td style='text-align: right'>\$$f_price</td>\n
<td>{$CarInfo[$i]['CurrentMiles']}</td>\n
<td>{$CarInfo[$i]['Engine']}</td>\n
<td>{$CarInfo[$i]['Transmission']}</td>\n
<td>{$CarInfo[$i]['DriveType']}</td>\n
<td>{$CarInfo[$i]['VIN']}</td>\n
<td>{$CarInfo[$i]['BoughtFrom']}</td>\n
<td>{$CarInfo[$i]['BoughtHow']}</td>\n
<td>{$CarInfo[$i]['LicensingFee']}</td>\n
<td>{$CarInfo[$i]['GasMileage']}</td>\n
</tr>\n";
echo "<tr><td colspan='4'><hr /></td></tr>\n";
}
echo "</table>\n";
?>
</body>
</html>
The following is the output.
\n"; echo "
\n"; for ($i=1; $i<=sizeof($CarInfo); $i++) { $f_price = number_format($CarInfo[$i]['Price'], 2); echo "\n $i.\n {$CarInfo[$i]['StockNumber']}\n {$CarInfo[$i]['Year']}\n {$CarInfo[$i]['Make']}\n {$CarInfo[$i]['Model']}\n {$CarInfo[$i]['Package']}\n \$$f_price\n {$CarInfo[$i]['CurrentMiles']}\n {$CarInfo[$i]['Engine']}\n {$CarInfo[$i]['Transmission']}\n {$CarInfo[$i]['DriveType']}\n {$CarInfo[$i]['VIN']}\n {$CarInfo[$i]['BoughtFrom']}\n {$CarInfo[$i]['BoughtHow']}\n {$CarInfo[$i]['LicensingFee']}\n {$CarInfo[$i]['GasMileage']}\n \n"; echo "
\n"; } echo "\n"; ?>
I wasn't sure how to search this, so sorry if this is a common problem.
Get that php out of those script tags! Put it all into one nice php block. Ideally you'd do something like have a "connect.php" page just for setting up your db connection then do an but it'll work on your page you have now.
Get rid of all those "\n"s. Those arnt helping anything. You dont need to have lines in your html, your browser will understand. (i'm assuming thats why you put them in). You had a bunch of crazy stuff going on when you created your table. Maybe you need it so its formatted pretty. I took it out. Lets get basic functionality working first. Table structure goes as follows: Table-head-row definition-closingTableTag.
Edit: Also i dont know why you had characters before and but make sure those are gone. And make sure you're saving your file as .php and not .html.
Try this, get back to us.
<!DOCTYPE html>
<html>
<head>
<title>Realistic Autos Inventory</title>
</head>
<body>
<?php
$user="Uhrmacher";
$host="localhost";
$password="";
$dbname="realistic autos";
$cxn= mysqli_connect($host, $user, $password, $dbname) or die("Failure to Communicate!");
function GetInventory($CarName){
$query = "SELECT * FROM inventory WHERE Make='$CarName'";
$result = mysqli_query($cxn, $query) or die ("Failure to Query!");
$index=1;
while($row=mysqli_fetch_query($result))
{
foreach($row as $colname => $value)
{
$array_multi[$index][$colname]=$value;
}
$index++;
}
return $array_multi;
}
$CarName = "Mustang";
$CarInfo = GetInventory($CarName);
echo "<h1>{$type}s</h1>";
echo "<table>";
//table header for every column you have. You could write a for loop to simplify
echo "<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr>";
for ($i=1; $i<=sizeof($CarInfo); $i++)
{
$f_price = number_format($CarInfo[$i]['Price'], 2);
echo "<tr>
<td>$i.</td>
<td>{$CarInfo[$i]['StockNumber']}</td>
<td>{$CarInfo[$i]['Year']}</td>
<td>{$CarInfo[$i]['Make']}</td>
<td>{$CarInfo[$i]['Model']}</td>
<td>{$CarInfo[$i]['Package']}</td>
<td>$f_price</td> //DONT GET FANCY YET, JUST MAKE SURE IT WORKS
<td>{$CarInfo[$i]['CurrentMiles']}</td>
<td>{$CarInfo[$i]['Engine']}</td>
<td>{$CarInfo[$i]['Transmission']}</td>
<td>{$CarInfo[$i]['DriveType']}</td>
<td>{$CarInfo[$i]['VIN']}</td>
<td>{$CarInfo[$i]['BoughtFrom']}</td>
<td>{$CarInfo[$i]['BoughtHow']}</td>
<td>{$CarInfo[$i]['LicensingFee']}</td>
<td>{$CarInfo[$i]['GasMileage']}</td>
</tr>";
}
echo "</table>";
?>
</body>
</html>
i have a list of emails on a database, which are brought onto the screen, this is coming from a previous page where you choose the category to add emails into.
The idea is for the user to check in the emails he wants to add to a connecting table that will join those two.
But i seem to be having problems. I have tried editing the page where i think the problem is, which is the , but no clue as to how i should edit it.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$idcategoria = $_GET["id"];
$query = "SELECT nome,email,id FROM email";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo"<form id='formulario' name='formulario' method='post' onsubmit='return validar(this);' action='../inserir/inserirmailcat.php'>";
echo "<br>";
echo "<button type='submit'>Submeter</button>";
echo "<tr align='center'><td>Nome</td><td>Email</td><td>Adicionar a Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if($campo=="nome")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="email")
{
echo "<td><b></b>".$valor. "\n</td>";
}
if($campo=="id")
{
echo "<td><input name='nome[".$valor."]' type='checkbox' value='Adicionar'></td></tr>";
}
}
echo "<input type='hidden' name='categoria' value='".$idcategoria."'>";
echo "</form>\n";
}
echo "</table>\n";
echo"</center>";
?>
This first page receives the ID from the previous one, and it lists a series of emails, where i check out the ones i want to add to a new table. And i try to pass them through a vector.
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$queryq = "SELECT id FROM email";
$resultsq = mysql_query($queryq) or die(mysql_error());
while ($rowq = mysql_fetch_assoc($resultsq)) {
foreach ($rowq as $campoq=>$valorq) {
$cat = $_POST["categoria"];
$username = $_POST['nome['.$valorq.']'];
if ($username != '')
{
$query = "INSERT INTO emailcategoria (email,categoria) VALUES ('".$username.",".$cat."')";
mysql_query($query) or die(mysql_error());
}
}
}
mysql_query($queryq) or die(mysql_error());
header("Location:../listar/listarcategoria.php");
?>
On this second page i try to add only the emails which have been selected onto a new table which will receive the email's ID and the category's ID, but it is giving me the following error "after a few different error's when i tried a diferent approach":
Notice: Undefined index: nome[8445] in C:\xampp\phpMyAdmin\trabalho\inserir\inserirmailcat.php on line 10
The error is given for all the email ID's.
UPDATED
Error is on this like
$username = $_POST['nome['".$valorq."']'];
Firstly, is it supposed to be 'nome' ?
Secondly change the syntax like this
$username = $_POST['nome['.$valorq.']'];
$username = $_POST['nome['".$valorq."']'];
Well that's wrong, as the syntax highlighting shows.
$username = $_POST['nome['.$valorq.']'];
Also, sanitise your input or (better) use prepared statements!
> xkcd
I'm using some crazy mixture of PHP/JavaScript/HTML/MySQL
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// Display a confirm box saying "Not everyone has entered a bid, continue?"
}
// If confirmed yes run more queries
// Else nothing
What is the best way to have this confirm box display, before completing the rest of the queries?
if($row != NULL) {
?>
<script>alert("not everyone has submitted their bid.");</script>
<?php
}
or
<?php
function jsalert($alert_message){
echo "<script type='text/javascript'>alert('".$alert_message."');</script>";
}
if($row!=null){
jsalert("Not everyone has submitted their bid.");
}
?>
You can't do this in 1 continuous block, as all of the PHP will execute before the confirm (due to server vs. client).
You will need to break these into 2 separate steps and have the client mediate between them:
part1.php:
<?php
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row != NULL) { ?>
<form id="confirmed" action="part2.php" method="post">
<noscript>
<label>Not everyone has entered a bid, continue?</label>
<input type="submit" value="Yes">
</noscript>
</form>
<script type="text/javascript">
if (confirm("Not everyone has entered a bid, continue?")) {
document.getElementById('confirmed').submit();
}
</script>
<?
} else {
include_once('part2.php');
}
?>
part2.php:
<?php
// assume confirmed. execute other queries.
?>
$query = "SELECT * FROM faculty WHERE submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
// more queries here
} else {
echo "<script>alert('Empty result');</script>";
}
Play with this code and you will get it to work eventually. I know you are not looking for just alertbox , instead you are looking for something like "yes or no" informational box. So check this out.
<?php
?>
<html>
<head>
<script type="text/javascript">
function displayBOX(){
var name=confirm("Not everyone has entered a bid, continue?")
if (name==true){
//document.write("Do your process here..")
window.location="processContinuing.php";
}else{
//document.write("Stop all process...")
window.location="stoppingProcesses.php";
}
}
</script>
</head>
<?php
$query = "SELECT * faculty SET submitted = 0;";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row != NULL) {
echo "<script>displayBox();</script>";
}
?>