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>";
}
?>
Related
i know this is simple..but i am unable to find the error..i have a login page where i take the input from user i.e. the username and password.then another page i am checking whether the values are present in the database or not.but neither it is giving me an error nor its working..moreover its not entering the first if condition..if ($result->num_rows > 0)
<body style="background-color:lightgrey;">
<?php
include('custdb.php');
session_start();
$uname=$_POST['username'];
$pass=$_POST['password'];
$sql = "SELECT * FROM `info` WHERE `username`='".$uname."';";
//echo $sql;
$result = $conn->query($sql);
echo"1";
echo $result;
if ($result->num_rows > 0)
{
echo"1";
while($row = $result->fetch_assoc())
{
if($uname==$row["username"])
{
header("location:custprofile.php");
}
else
{
header("Location:custindex.php");
}
}
}
else
{
echo "invalid input";
echo '<h4 align="left">LOGIN </h4>';
}
?>
Try to change this portion of your code,
$uname=$_POST['username'];
$pass=$_POST['password'];
$sql = "SELECT * FROM `info` WHERE username='".$uname."' AND password='".$pass."'";
I try to update the data in the database, but when I run the code, there is no error message appear, looks like its a logical error but I still don't have any clue about what is happening with my code.
Here is the code
<?php
include("conn.php");
SESSION_START();
if($_SESSION["loggedin"]!="true"&& $_SESSION['login'] != '')
header("location:login.php");
$aid = $_SESSION["usr"];
$result = mysql_query("select r.CustomerID from customer c inner join results r on r.CustomerID = c.CustomerID where c.Username = '".$aid."' ");
if (false === $result) {
echo mysql_error();
}
$row = mysql_fetch_assoc($result);
?>
<?php
if (isset($_POST["submitbtn"]))
{
$bookid = $_POST["bookid"];
$LP = $_POST["LP"];
$budget = $_POST["budget"];
$smokep = $_POST["SmokeP"];
$spreq = $_POST["sp_req"];
$query = mysql_query("UPDATE `results` SET LP = '$LP', budget = '$budget', SmokeP = '$smokep', sp_req = '$spreq'
WHERE results.BookID = '".$bookid."' and results.CustomerID = '".$result."'");
if (false === $query)
{
echo mysql_error();
}
?>
<script type = "text/javascript">
alert("Amendment Saved!!");
</script>
<?php
}
?>
Is the error coming from the select query? Or the if statement for the submitbtn went wrong?
First of all you cant put session start here
You must put it on the first line after open php tag
Second
update res='$ new_value' where ...
Tell me if it's not usefull to try another solution
this is my login.php file
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
//echo "Name ".$_POST["name"];
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>
One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ? The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ? And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.
Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php
Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.
//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();
I don't know what do you mean but thats how i query mysqli
$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");
if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
echo $rows['name'] . '<br />' ;
}
} else {
echo 'Query Failed!';
}
i think thats what you mean
EDIT:
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name = null ;
$password= null ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
$password = mysqli_real_escape_string($conn, $_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){
print "rows are ".mysqli_num_rows($result)"<br>";//number of rows
if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
echo "you are logged in<br>";
while ($row = mysqli_fetch_assoc($result)){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
mysqli_free_result($result);
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
mysqli_close($conn);
?>
</body>
</html>
try to change this query
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")
to
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")
then you will get only one row , and try to change
$row = $result->fetch_assoc()
to
$row = $result->mysqli_fetch_row()
then you can display the results by colomn number instead of colomn name
<?php
mysql_connect("abc.com","user","password");
mysql_select_db("database name");
$query1="select * from table_name";
$exe1= mysql_query($query1);
$row= mysql_fetch_assoc($exe1);
if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) {
echo "Login successfully";
} else {
echo "error in login";
}
?>
enter your column name in row["email"] and $row["password"]
I"m attempting to display some data I've sent from ajax to a php file, however for some reason its not displaying it on the page. The way it works it I enter a search term into a input field, and a ajax script post the value to a php script, which return the database value requested back.
error_reporting(E_ALL);
ini_set('display_errors', '1');
if (isset($_POST['name']) === true && empty($_POST['name']) === false) {
//require '../db/connect.php';
$con = mysqli_connect("localhost","root","root","retail_management_db");
$name = mysqli_real_escape_string($con,trim($_POST['name']));
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = {$name}";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$loc = $row['location'];
echo $loc;
}//close While loop
} else {
echo $name . "Name not Found";
}
}
html form:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Retail Management Application</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit" value="Grab">
<div id="name-data"></div>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="js/global.js"></script>
</body>
</html>
You're appending a MySQL error result to your query, and you're trying to query a query result, try the following:
$query = "SELECT `names`.`location` FROM `names` WHERE`names`.`name` = '$name'";
$result = mysqli_query($con, $query);
if (mysqli_num_rows($result) > 0) {
Edit:
{$name} that is a string and should be quoted instead.
change it to '$name' in the where clause.
Using:
$result = mysqli_query($con, $query) or die(mysqli_error($con));
will provide you with the reason as to why your query failed.
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.