Okay, so I am trying to display text when something goes wrong. I want to have it so that if the page number is too high (above 3 in my case) it will display an error. Disregard the accessing mySQL database.
<?php
function get($name)
{
return isset($_REQUEST[$name]) ? $_REQUEST[$name] : '';
}
function is_valid_index($index,$array)
{
return $index >= 0 && $index < count($array);
}
?>
<?php
//Variables
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "pass";
$dberror = "You have failed to connect to the database!";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass) or die ($dberror);
$select_db = mysqli_select_db($conn, "database") or die ("Couldn't Select Database");
?>
<form>
<?php
$page = array('Select List','Users', 'Groups');
echo '<select name="Lists">';
for($i = 0;
$i < count($page);
$i++)
{
echo '<option value="'.($i + 1).'">'.$page[$i].'</option>';
}
echo '</select>';
?>
<input type='submit'>
</form>
<?php
if(get('page'))
{
$page_id = get('page');
if(is_valid_index($page_id-1,$page))
{
echo "You have selected".$page[$page_id-1];
}
else
{
echo '<span style="color:red">Invalid Page</span>';
}
}
?>
Got the tutorial from this video: https://www.youtube.com/watch?v=SaRh2HauIXY
change this
echo '<select name="Lists">';
into this
echo '<select name="page">';
this way the function get('page') will return true and the if block will execute and so will your echo calls
Related
So I'm trying my hand at creating php methods from scratch. My classes aren't exactly classes yet, I'm still working on that. Anyway, my issue's I can't seem to get the values I expect from my database. Here's a snippet of my code:
file1.php
<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
return $item["Name"];
}
}
}} ?>
Here's the snippet of how I call the above method in file2.php
<?php ini_set("display_errors", 1);
include_once("file1.php");
$con = dbConnect();
$updateStat = false; ?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<option value="<?php $con->getCategory() ?>"></option>
</select>
</div>
I've tried printing a message at the start of the method to see if the it's being called but the message did not print either so I was wondering, what am I possibly missing here?
I think you have serveral mistakes in your code ... i guess, you don't use OOP (classes) so i modfiy a example which should work .. .if not, please post error messages
file1.php
function getCategory($cn) {
$out = array();
if($cn == null) {
echo "Failed to connect to database.";
} else {
$fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
if(mysqli_num_rows($fetchQuery) > 0) {
while($item = mysqli_fetch_array($fetchQuery)) {
$out[] = $item["Name"];
}
}
return $out;
}
}
fil2.php
<?php
ini_set("display_errors", 1);
require_once("file1.php");
$con = dbConnect();
$updateStat = false;
$res = getCategory($con);
?>
<div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php
foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>
I am making online examination.. the data are passing from page to examination page. but the value of radio button is not passing from examination page to result page. I have checked that the course name and subject names are passing. I have added the timer section. Which is working good. The value of radio button inside the while is not passing to result..
EXAM CODE
<html>
<head>
<title>EXAM</title>
</head>
<body>
<?PHP
//$i=1;
$j=1;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
if ($db_found)
{ session_start();
$i=$_SESSION['$i'];
$sub = $_SESSION['$sub'];
/*if(isset($_POST['b_subject']))
{
$selected_button=$_POST['subject'];
if($selected_button=='subject1')
$_SESSION['$sub']= "GK";
else if($selected_button=='subject2')
$_SESSION['$sub']="math";
else
print "error";
}*/
if(isset($_POST['subject'])){
$selected_button=$_POST['subject'];
}
else
{
$selected_button="default button";
}
while($j<$i)
{
if($selected_button=='subject'.$j)
$s= $sub[$j];
$j++;
}
//print $_SESSION['$sub'];
//print $selected_button;
//print $_SESSION['$cour'];
//print
// //assign $_SESSION['array'] to $array
//print $sub[1];
/* foreach($sub as $value) {
print $value; //print $array contents
}*/
$c = $_SESSION['$cour'];
//$s = $_SESSION['$sub'];
$SQL = "SELECT ques FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
echo '<FORM name ="form1" method ="post" action="result_a.php" >';
while ( $db_field = mysql_fetch_assoc($result) )
{
print $db_field['ques']."<BR>";
?>
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '1'>YES
<Input type = 'Radio' Name ='ques<?PHP echo $i;?>' value= '0'>NO
<br>
<?PHP
$i++;
}
$_SESSION['$i']= $i;
//$_SESSION['ques'] = $que;
$_SESSION['$sub'] = $s;
echo '<input type="submit" name="submit" id="submit" value="SUBMIT"/></FORM>';
mysql_close($db_handle);
}
$targetDate = time()+(330*60) + (1*30);
$actualDate = time()+(330*60);
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
?>
<h1>Time Left</h1>
<script type="text/javascript">
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").innerHTML = hours+" hours : "+minutes+" minutes : "+seconds+" seconds";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') { seconds = "00"; window.clearTimeout(SD);
window.alert("Time is up. Press OK to continue.");
window.location = "http://localhost/result_a.php"
}
}
</script>
<body onload="setCountDown();">
<div id="remain"><?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?></div>
</body>
</html>
Inside the result the line " $selected_radio = $_POST['ques'.$i];" is showing error that "Undefined index: ques1" , "Undefined index: ques2", ... so on....
RESULT CODE
<html>
<head>
<title>RESULT</title>
<body>
<?PHP
$i=1;
$count=0;
$ans= "";
session_start();
//$i=$_SESSION['$i'];
$s=$_SESSION['$sub'];
$c=$_SESSION['$cour'];
//$que[]=$_SESSION['ques'];
//print $c.$s;
$user_name = "root";
$password = "";
$database = "online_exam";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database,$db_handle);
$SQL = "SELECT ans FROM ques_ans WHERE course='$c' AND subj='$s'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_array($result) )
{
$selected_radio = $_POST['ques'.$i];
if ($selected_radio == '1')
{
$ans='1';
}
else if ($selected_radio == '0')
{
$ans='0';
}
if($ans==$db_field['ans'])
$count++;
$i++;
}
print $count;
?>
</body>
</html>
</head>
you never define $i = anything before you attempt to perform $i++;, you cannot autoincrement an integer without declaring it's starting value.
Therefore your fields are all actually just
name="ques"
Without any integer appended to them. Define $i = 1; or $i = 0; depending on your desire, and this will be resolved.
i have a php page called page1.php with this form
<form id="myForm" action="page2.php" method="post">
<label for="name">a label:</label><input type="submit" name="SubmitCar" value="Done" id="fbutton" /> <br />
<br />
<select name="selectCar">
<?php
session_start();
$user = "cardatabase";
$password = "";
$host = "";
$database = "my_cardatabase";
$connessione = mysql_connect($host, $user, $password) or die( mysql_error() . " <br/> could not connect to server");
mysql_select_db($database, $connessione) or die( mysql_error() . " <br/> could not connect datbase");
$id = $_SESSION['myid'];
$query = "select IDCar
from Car";
$result = mysql_query($query, $connessione) or die(mysql_error());
if( mysql_num_rows($result) > 0 ) {
$array = array();
$i = 0;
while ($row = mysql_fetch_array($result)) {
$array[$i] = $row['IDCar'];
++$i;
}
for ($i = 0; $i < count($array); ++$i) {
echo "<option value='$array[$i]'>$array[$i]</option>";
}
}
mysql_close();
?>
</select>
</form>
Simply fill the select box from DB. Now here's the problem. When i reach page2.php i need the value of the select box and i tried this
page2.php
<?php
$value = $_POST['selectCar'];
?>
But it's not working, so i tried to use sessions in this way
page1.php
</form>
<?php
if(isset($_POST['SubmitCar'])){
$_SESSION['idAuto'] = $_POST['selectCar'];
}
?>
out of the form, but still not working. What can i do to get this value in page2.php??
Try using this code to build your <option> , and use mysqli when working with the database
$result = mysqli_query($connessione, $query) or die(mysql_error());
if( mysqli_num_rows($result) > 0 ) {
$i=0;
while ($row = mysqli_fetch_row$result)) {
echo "<option value='".$row[$i]."'>".$row[$i]."</option>";
$i++;
}
}
Also, it's not indicated to have mysql tables with names in uppercase, or fields with names in uppercase.
Page2.php
You forgot to echo it.
<?php
$value = $_POST['selectCar'];
echo $value;
?>
I found a simple workaround for my problem. It might not be perfect but it works.
i deleted the action="page2.php" in the form of page1
in page1.php add this code outside the form
This will do the trick
if(isset($_POST['SubmitCar'])){
$_SESSION['idCar'] = $_POST['selectCar'];
header('Location:page2.php');
}
This question already has answers here:
Issue with PHP MySQL and insert into UTF-8 [closed]
(3 answers)
Closed 10 years ago.
I have a problem with php & mysql, insert to database using utf-8.
first file:
addsite:
<?php
include 'header.php';
if(isset($data)) {
foreach($_POST as $key => $value) {
$posts[$key] = filter($value);
}
if(isset($posts['type'])){
if($posts['url'] == "http://" || $posts['url'] == ""){
$error = "Add your page link!";
}else if($posts['title'] == ""){
$error = "Add your page title!";
}else if(!preg_match("/\bhttp\b/i", $posts['url'])){
$error = "URL must contain http://";
}else if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $posts['url'])){
$error = "Please do not use special characters in the url.<";
}else{
include "plugins/" . $posts['type'] . "/addsite.php";
}
}
?>
<div class="contentbox">
<font size="2">
<li>Pick the type of exchange you are promoting from the dropdown menu.</li>
<li>Set the amount of coins you wish to give per user complete(CPC).</li>
<li>The higher the amount of coins the higher the Links position.</li>
</div>
<div class="contentbox">
<div class="head">Add Site</div>
<div class="contentinside">
<?php if(isset($error)) { ?>
<div class="error">ERROR: <?php echo $error; ?></div>
<?php }
if(isset($success)) { ?>
<div class="success">SUCCESS: <?php echo $success; ?></div>
<?php }
if(isset($warning)) { ?>
<div class="warning">WARNING: <?php echo $warning; ?></div>
<?php } ?>
<form class="contentform" method="post">
Type<br/>
<select name="type"><?php $select = hook_filter('add_site_select', ""); echo $select; ?></select><br/><br/>
Link<br/>
<input name="url" type="text" value="<?php if(isset($posts["url"])) { echo $posts["url"]; } ?>"/><br/><br/>
Title<br/>
<input name="title" type="text" value="<?php if(isset($posts["title"])) { echo $posts["title"]; } ?>"/><br/><br/>
Cost Per Click<br/>
<?php if($data->premium > 0) { ?>
<select name="cpc"><?php for($x = 2; $x <= $site->premcpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php }else{ ?>
<select name="cpc"><?php for($x = 2; $x <= $site->cpc; $x++) { if(isset($posts["cpc"]) && $posts["cpc"] == $x) { echo "<option selected>$x</option>"; } else { echo "<option>$x</option>"; } } ?></select><br/><br/>
<?php } ?>
<input style="width:40%;" type="Submit"/>
</form>
</div>
</div>
<?php
}
else
{
echo "Please login to view this page!";
}
include 'footer.php';
?>
second file , plugin addsite.php
<?php
$num1 = mysql_query("SELECT * FROM `facebook` WHERE `url`='{$posts['url']}'");
$num = mysql_num_rows($num1);
if($num > 0){
$error = "Page already added!";
}else if(!strstr($posts['url'], 'facebook.com')) {
$error = "Incorrect URL! You must include 'facebook.com'";
}else{
mysql_query($qry);
mysql_query("INSERT INTO `facebook` (user, url, title, cpc) VALUES('{$data->id}', '{$posts['url']}', '{$posts['title']}', '{$posts['cpc']}') ");
$success = "Page added successfully!";
}
?>
when i write arabic language in the form and submit ,
it went to database with unkown language like :
أسÙ
database collaction : utf8_general_ci
<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');
$host = "localhost"; // your mysql server address
$user = "z*******"; // your mysql username
$pass = "m********"; // your mysql password
$tablename = "z*******"; // your mysql table
session_start();
$data = null;
if(!(#mysql_connect("$host","$user","$pass") && #mysql_select_db("$tablename"))) {
?>
<html>
MSQL ERROR
<?
exit;
}
include_once 'functions.php';
require_once "includes/pluggable.php";
foreach( glob("plugins/*/index.php") as $plugin) {
require_once($plugin);
}
hook_action('initialize');
$site = mysql_fetch_object(mysql_query("SELECT * FROM settings"));
?>
after removing
$posts[$key] = filter($value); "
from header.php
The output shift from:
To:
& Oslash; & pound; & Oslash; ³& Ugrave
to : Ù Ù Ù
header file : http://zwdha.com/header.txt
You might need to add some ini_set statements if your db is full utf8: http://www.polak.ro/php-mysql-utf-8.html
This a very basic insert query to see if you can insert data in you database with PHP.
<?php
function inserting_data() {
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets inserted into your table.
* If some of your columns are set to not null you should add them tot this insert query.
*/
$query = "INSERT INTO facebook (`title`) VALUES('test_title'), ('test_title1')";
mysqli_query($link, $query);
}
mysqli_close($link);
}
?>
This is a very basic select query to retrieve data form your database.
<?php
function selecting_data(){
$host = "host";
$user = "username";
$password = "password";
$database = "database";
$charset = "utf8";
$link = mysqli_connect($host, $user, $password, $database);
mysql_set_charset($charset, $link);
IF (!$link) {
echo('Unable to connect to the database!');
} ELSE {
/*
* this just to test if something gets returned from your table.
*/
$query = "SELECT * FROM facebook";
$result = mysqli_query($link, $query);
while ($rows = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $rows['title'];
}
}
mysqli_close($link);
}
?>
My advise is to first test if you can get data in your database and retrieve it. By trial and error you will need to solve your question. B.T.W. I have used MYSQLI_ function instead of MYSQL. The mysql_ functions will depreciate soon. Hope this helps.
a - you should not use mysql_ functions. use PDO. this error is one of the reasons.
b - mysql_set_charset('utf8');
c - are the columns you are trying insert data using utf8_general_ci ?
d - on my.cf set default-character-set and character-set-server
if this doesn't work read this:
http://www.oreillynet.com/onlamp/blog/2006/01/turning_mysql_data_in_latin1_t.html
and this:
http://www.phpwact.org/php/i18n/utf-8
if after that you still dont get it right, make sure to listen to people and use PDO.
I created a form which creates table with entered number of rows and columns on form. I want to create that entered fields table into database and save its values into database Table. Guide me what I should use.
My code:
<?php
global $Host;
global $Username;
global $password;
global $database;
function getConnection()
{
$Host = "localhost";
$Username = "root";
$password = "";
$database = "labdata";
$oMysqli = new mysqli($Host,$Username,$password,$database);
return($oMysqli);
}
?>
<html>
<head>
<title>aa</title>
</head>
<body>
<form name="report Creation" method="post">
<label for='Table'>Define Table</label>
<label for='column'>Row</label>
<input type="text" name="column"></input>
<label for='rows'>Column</label>
<input type="text" name="rows"></input>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
<?php
function displayData($column,$rows)
{
echo "<table border='1' align='center'>";
for($i = 0;$i<$_POST['column'];$i++)
{
echo "<tr>".$i."</tr>";
for($j = 0; $j <$_POST['rows'];$j++)
{
echo "<td>" ."<input type=\"text\" name='column_$i[$j]'>"."</td>";
}
}
echo "</table>";
echo "<form>";
echo "<input type=\"submit\" name=\"ok\" value=\"ok\">";
echo "</form>";
//function displaydata($column = NULL) {if($id == NULL) Event::run('system.52');}
}
if(isset($_POST['submit']))displaydata();// Show data INSIDE form
{
$query = "CREATE TABLE Cars('$columns[$j]')";
$oMysqli = getConnection();
$oMysqli->query($query);
$Insert = "INSERT INTO Cars(Id,column[$j]) VALUES($Id,$column)";
$oMysqli = getConnection();
$oMysqli->query($Insert);
if(isset($_POST['ok']))
{
$plength = count($_POST['column']);
for($j=0;$j<$plength;$j++)
{
$b = $_POST['column'][$j];
$pa = array('column' => $b['column']);
foreach($pa as $l => $m)
{
$pa[$l] = mysql_real_escape_string($m);
}
$columns = $pa['column'];
$columns = $_POST['column'][$j];
for($n=0;$n<$columns;$n++)
{
$x= $_POST['column'][$j];
$ab = array('column' => $c['column']);
foreach($t as $u => $n)
{
$ab[$u] = mysql_real_escape_string($n);
}
$columns = $ab['column'];
$columns = $_POST['column'][$j];
}
}
}
if($result = $mysqli->query($Insert))
{
$k=0;
$column = explode(",",$_POST['columns']);
foreach($column as $c)
{
echo "<td><b>$c</b></td>\r\n";
}
echo "</tr>";
}
}
?>
To answer you question: creating a table is executing a SQL statement against the server.
You should rethink your strategy, creating a table based on user input is bad design.
Use the 'CREATE TABLE' syntax in your query.
All info about it: http://dev.mysql.com/doc/refman/5.1/en/create-table.html