I am developing an application that has a question bank through which i want to generate a question paper randomly. I am using PHP and HTML. I am using html as my front end and for back end PHP. I have developed the code but there is a problem with it, its generating 4 textarea 2 for one question and i am unable to debug it
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "rgpv";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ques FROM bank WHERE sub='$_POST[sub]' ORDER BY RAND() LIMIT 2";
$result = $conn->query($sql);
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<!-- Calling CSS -->
<link rel="stylesheet" href="css/reset.css">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<!--File for fonts-->
<link rel='stylesheet prefetch' href='css/bootstrap.css'>
<link rel='stylesheet prefetch' href='css/font-awesome.min.css'>
<link rel="stylesheet" href="css/style.css">
</head> <!-- end Head -->
<body background="images/journal.jpg">
<!-- Mixins-->
<!-- Form Title-->
<div class="pen-title">
<h1>University Institute of Technology- RGPV</h1><h2>Random Question Paper Generator Portal</h2>
</div>
<fieldset class="form-group">
<label for="exampleTextarea">Question 1</label>
<textarea class="form-control txt" id="name" rows="3" value="" disabled><?php echo $row["ques"]; ?></textarea>
</fieldset>
<fieldset class="form-group">
<label for="exampleTextarea">Question 2</label>
<textarea class="form-control txt" id="name" rows="3" value="" disabled><?php echo $row["ques"]; ?></textarea>
</fieldset>
</body>
</html>
<?php
}
?>
<?php
function get_question()
{
// Connect to your database storing your questions
$connection = new mysqli("hostname", "username", "password", "database");
if($connection->connect_errno)
{
die("Error connecting to database.");
}
// Load all your questions from your database into an array
$query = "SELECT * FROM questions";
$result = $connection->query($query);
$questions = $result->fetch_all();
// Randomly select a question from your array to output
$number = rand(0, count($questions) - 1);
return $questions[$number];
}
$question = get_question();
// Use var_dump() to view the raw output from your database
// You can now output your question and format it however you'd like
var_dump($question);
// You can call this function as many times as you'd like using a loop
for($i = 0; $i < 10; $i++)
{
$question = get_question();
// Output your question properly formatted here
}
?>
Use a function like this & pull data from your db :
when ever you call it like : UniqueRandomNumbersWithinRange(0,25,5)
You will get an array $quantity of jumbled numbers between $min to $max.
From the backend just pull questions in the array order.
Related
I am trying to create a working HTML Login Page with a PHP script that compares the login data with the Database.
I have been trying to get this working for some time now but it doesent really work. This is the Error Code I get when I press on the Login Button:
Cannot POST /connectivity.php
I created a Database (called leftover_youth)with XAMPP.
UserNameID
userName
pass
This at the moment the HTML code for the whole page.
<html>
<head lang="en">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" name="viewport">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="scripts/app.js"></script>
<link rel="stylesheet" href="css/stylesheet.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title>Project Bootstrap</title>
</head>
<body>
<header>
<div class="navlogo">
<a href="index.html">
<h1 class="Logo">Leftover Youth</h1>
</a>
<a href="index.html">
<img class="logoo" src="img/logoo.png" alt="firstimage">
</a>
</div>
</header>
<div>
<fieldset style="width:30%">
<legend>LOG-IN HERE</legend>
<form method="POST" action="connectivity.php"> User <br>
<input type="text" name="user" size="40"><br> Password <br>
<input type="password" name="pass" size="40"><br>
<input id="button" type="submit" name="submit" value="Log-In">
</form>
</fieldset>
</div>
</body>
</html>
PHP:
<?php define('DB_HOST', 'localhost');
define('DB_NAME', 'leftover_youth');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
$ID = $_POST['user'];
$Password = $_POST['pass'];
function SignIn()
{
session_start(); //starting the session
if(!empty($_POST['user'])) //checking User data
{
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass']))
{
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else
{
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...";
}
}
}
if(isset($_POST['submit'])) { SignIn();
}
?>
You need to check the directory/path of connectivity.php
also move the $ID and $Password in to the post check
if(isset($_POST['submit'])) { SignIn();
$ID = $_POST['user'];
$Password = $_POST['pass'];
}
First of all avoid using mysql which is long back deprecated, instead use mysqli
There are few solutions for your problem.
The way with MySQLi would be like this:
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
To run database queries is also simple and nearly identical with the old way:
// Old way
$query = mysql_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
// New way
$query = mysqli_query("SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysql_error());
i need help to style the output when i use php and search for for example names in my database...
The output will just be default text like amateur echo...
This is my code, and a screenshot of my homepage where i want the output to come inside the div... and to be like the rest of the text?
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="contact">
<h1>Indtast postnummer & få bynavn:</h1>
<form action="select.php" method="POST">
Postnummer: <input type="text" name="formnavn"/>
<input type="submit" value="SEND"/>
</form>
<form action="index.php">
<input style="" type="submit" value="Startsiden">
</form>
</div>
<?php
$server = "localhost";
$brugernavn = "root";
$kode = "";
$db = "dbintro2f";
mysql_connect($server , $brugernavn , $kode);// or die(mysql_error());
//echo "Forbundet til mysql server<br/>";
mysql_select_db($db); //or die(mysql_error());
$postnr = filter_input(INPUT_POST, 'formnavn');
$data = mysql_query("SELECT * FROM postnummer WHERE (postnr) = $postnr" ) or die(mysql_error());
$info = mysql_fetch_array($data);
echo "Postnummer: " . $info['postnr'] . "<br/>";
echo "By: " . $info['bynavn']. "<br/>";
?>
</body>
</html>
The codes in netbeans
http://imgur.com/yNRcE56
The webpage and used paint to show how i want it to be in a div below my search field.
http://imgur.com/ZRlzb9X
Since PHP was invented as template language, you are still free to use HTML whereever inside it like:
...
$info = mysql_fetch_array($data);
?>
<div class="mydiv">
<?php
echo "Postnummer: " . $info['postnr'] . "<br/>";
...
Three lines in the middle of snippet (including closing PHP tag ?> and next opening <?php) are to output <div> on the page. When the parser encounters closing PHP tag, it stops treating the source as PHP code and starts to simply output it.
Hope it helps.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
there are three diffrent files all in php please help mysql doen't returns a value from the database ?
//login.php
<?php
session_start();
include("includes/html_codes.php");
if (isset($_POST["email"])&&isset($_POST["password"])) {
$username = mysql_real_escape_string($_POST["email"]);
$password = mysql_real_escape_string($_POST["password"]);
if (!empty($username)&&!empty($password)) {
$query = mysql_query('SELECT * FROM users WHERE email=("$username") AND password=("$password")');
$count = mysql_num_rows($query);
$row = MySQL_fetch_row($query);
if($row==1){
echo 'ok';}
else {
echo 'Wrong Username or Password';
}
} else {
echo 'You must provide a username and password.';
} }
?>
##i guess the query is incorrect please help new to php##
<html xmlns="http://www.w3.org/1999/xhtml">
<html lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="css/main.css"/>
<link rel="stylesheet" href="css/form.css"/>
<link rel="stylesheet" href="css/register.css"/>
</head>
<body style="background-color:#EEEEEE">
<header>
<?php topBarm(); ?>//some function which works perfectly
</header>
<div id="wrapperLogin">
<center>
<form id="generalForm" class="container" action="<?php echo $current_file; ?>" method="POST">
<div class="field">Username: <input type="email" name="email" id ="email" class="input1"> </div> <div class="field">Password: <input type="password" name="password" id="password" class="input1"></div></center>
<center><div class="field"><input type="submit" class="buton" value="Log in" ></div>
</form></center></html>
""<please read the index.php file also it contains some important stuff>"
index file is including all the files so i didn't need to include it in login.php
//index.php
<?php
require 'includes/core.php';
require 'includes/connect.php';
include("login.php");
echo $current_file;
?>
##connection is established with this file##
>this code works perfectly
//connect.php
<?php
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'my_user';
$mysql_pass = '';
$mysql_db = 'my_database';
if(!#mysql_connect($mysql_host, $mysql_user, $mysql_pass)||!#mysql_select_db($mysql_db)) {
die(mysql_error());
}
echo 'Connected!'
?>
Your query is badly formed. Try
$query = mysql_query("SELECT * FROM users WHERE email='" . $username . "' AND password='" . $password . "');"
Also, note that the mysql_ functions are deprecated. Update your code to mysqli or PDO.
First of all why do you have echos in the connection.php and why are you including so many files?
To learn basic debugging, you can do something like this with the result you are getting on your queries:
<pre>
<?php echo print_r($result) ?>
</pre>
Assuming you are doing a mysql_fetch_assoc or something similar with the result of the MySQL query
the variable enclosed in single quotes will not be displayed
$query = mysql_query("SELECT * FROM users WHERE email='".$username."' AND password='".$password."'");
I want to save an unordered list to a column in a database. How can i do this ?
CHESSE
HAM
CREATE TABLE INGREDIENTE ( name varchar(20), ingredients varchar(30);
I want to put the list in the ingredients part.
Here is my code in the html and js i use to create the list.
function selectIngredient(select)
{
var $ul = $(select).closest('.ui-select').prev('ul');
console.log($ul[0])
if ($ul.find('input[value=' + $(select).val() + ']').length == 0) {
console.log('s')
$ul.append('<li onclick="$(this).remove();">' +
'<input type="hidden" name="ingredients[]" value="' +
$(select).val() + '" /> ' +
$(select).find('option:selected').text() + '</li>');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Ingredient</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="themes/receta.min.css" />
<link rel="stylesheet" href="themes/receta.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
<script src="recetas.js"> </script>
</head>
<body>
<form action="insert.php" method="post">
Receta: <input type="text" name="receta">
Ingredientes: <input type="text" name="ingredientes">
<input type="submit">
<label>Ingredientes</label>
<ul>
</ul>
<select onchange="selectIngredient(this);">
<option value="Cheese">Cheese</option>
<option value="Olives">Olives</option>
<option value="Pepperoni">Pepperoni</option>
<option value="Milk">Milk</option>
</select>
</body>
</html>
<?php
$dbhost = 'localhost';
$dbuser = 'alanis_lozano';
$dbpass = '20Anahuac12';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'alanis_recetas';
mysql_select_db($dbname, $conn);
$sql="INSERT INTO Recetas (receta, ingredientes)
VALUES
('$_POST[receta]',$ingredientes = join(',', $_POST['selections'])";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn);
?>
What you really want to do here is store ingredients in a delimited fashion, and format them into a list on output.
Try something like this:
<form action="save.php">
<input type="text" name="name" />
<textarea name="ingredients"></textarea>
<button type="submit">Save</button>
</form>
save.php - Replace any delimiter character with a newline (\n) character before saving
<?php
$name = $_GET["name"];
$name = mysqli_real_escape_string($name);
$ingredients = $_GET["ingredients"];
$ingredients = mysqli_real_escape_string($ingredients);
$ingredients = preg_replace("/[,\.\n\t]+/", "\n", $ingredients);
display.php - Before displaying, split up your ingredients by the newline character and render them in a UL
echo "<ul>";
$ingredients = explode('\n", $ingredients);
for ($i = 0; $i < count($ingredients); $i++) {
echo "<li>{$ingredients[$i]}</li>";
}
echo "</ul>";
You could convert the list into a comma delimited string:
$ingredients = join(',', $_POST['selections']);
In the dom you can name the select box selections.
I am trying to create an autocomplete field using JQuery, which receives its autocompletions from a mysql database.
Index.php:
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - PHP Backend</legend>
<label for="state">State (abbreviation in separate field): </label>
<input type="text" id="college" name="college" />
<input type="submit" name="submitBtn" value="Submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submit'])) {
echo "<p>";
while (list($key,$value) = each($_POST)){
echo "<strong>" . $key . "</strong> = ".$value."<br />";
}
echo "</p>";
}
?>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
search.php:
/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'college';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
It's currently retrieving correctly from the database, because it's getting the correct number of autocompletions. However, they're all blank. It appears to not actually be feeding "name" back into the field and I can't seem to figure out why. Any ideas?
Without seeing the autocomplete code you are using, I would say that you need a 1-dimensional array instead of a 2-dimensional one as you are generating now.
You could try changing:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
To:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, $row['name']);
}
edit: check the api documentation, you need to build your array differently, something like:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}