I want to pass a variable to next page but i doesn't seem to work as expected. I have done samething on a different page but now it dosen't work.
This is the metod im using to pass the variables (email.php):
<div class='alternativ'> <td width="50%" style=" padding:5px;"> <form method='GET' action='excelimport.php'> <input type='hidden' name='pidnew3' value='$pidnew2'> <input type="submit" name="submit"> </form></td> </div>
and in excelimport.php i have this:$pidnew4 = $_POST['pidnew3'];
Im getting 2 error in excelimport.php:
Notice: Undefined index: pidnew3 in D:\home\site\wwwroot\devlopment\excelimport.php on line 77
its reffering to this: $pidnew4 = $_POST['pidnew3'];
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\home\site\wwwroot\devlopment\excelimport.php on line 102
and this is reffering to this: $recResult = mysql_fetch_array($sql);
I have this php (email.php) page that i want to pass to another.:
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions2.php';
include_once 'includes/config.php';
error_reporting(-1); ini_set( 'display_errors', 1 );
//Start av sessions
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'Inloggad';
} else {
$logged = 'utloggad';
}
$uploadedStatus = 0;
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
}
$storagename = "discussdesk.xlsx";
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename);
$uploadedStatus = 1;
}
} else {
echo "Ingen fil vald <br />";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Kandidater</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.709">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="css/bootstrap.min.css">
<!-- jQuery library -->
<script src="js/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="shortcut icon" href="logo/wfmini.png">
<script type="text/javascript" language="javascript">
function checkedbox(element) {
var checkboxes = document.getElementsByTagName('input');
if (element.checked) {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = true;
}
}
} else {
for (var i = 0; i < checkboxes.length; i++) {
console.log(i)
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
}
</script>
<script src="js/tinymce/js/tinymce/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
</head>
<body class="dashboardadmin">
<ss="container-fluid" style="width:50%;">
<br>
<center><h3>Skicka email till kandidater</h3></center>
<br>
<p>Välj kandidater</p>
<form method="post" action="">
<?php
$pidnew2 = $_GET['pidnew'];
// Retrieve Email from Database
$getemail = mysql_query("SELECT * FROM Email_Users WHERE pid='".$pidnew2."'");
if (!$getemail) die('MySQL Error: ' . mysql_error());
echo '<table class="table table-bordered">';
echo "<thead>
<tr>
<th><input type='checkbox' onchange='checkedbox(this)' name='chk'/></th>
<th>Förnamn</th>
<th>Efternamn</th>
<th>Email</th>
</tr>
</thead>";
if (mysql_num_rows($getemail) == 0) {
echo "<tbody><tr><td colspan='3'>No Data Avaialble</td></tr></tbody>";
}
while ($row = mysql_fetch_assoc($getemail)) {
echo "<tbody><tr><td><input value='".$row['Email']."' type='checkbox' name='check[]'/></td>";
echo "<td >".$row['fornamn']."</td>";
echo "<td >".$row['efternamn']."</td>";
echo "<td >".$row['Email']."</td></tr></tbody>";
}
echo "</table>";
?>
</form>
</center>
<br>
</div>
<table width="600" style="margin:115px auto; background:#f8f8f8; border:1px solid #eee; padding:10px;">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<tr><td colspan="2" style="font:bold 15px arial; text-align:center; padding:0 0 5px 0;">Ladda upp kandidater</td></tr>
<tr>
<td width="50%" style="font:bold 12px tahoma, arial, sans-serif; text-align:right; border-bottom:1px solid #eee; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Välj fil</td>
<td width="50%" style="border-bottom:1px solid #eee; padding:5px;"><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td style="font:bold 12px tahoma, arial, sans-serif; text-align:right; padding:5px 10px 5px 0px; border-right:1px solid #eee;">Send</td>
<div class='alternativ'>
<td width="50%" style=" padding:5px;">
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form></td>
</div>
</tr>
</table>
<?php if($uploadedStatus==1){
header('Location: excelimport.php');
}?>
</form>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-38304687-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
And here's the other one (excelimport.php):
<?php
include_once 'includes/db_connect.php';
include_once 'includes/functions2.php';
include_once 'includes/config.php';
error_reporting(-1); ini_set( 'display_errors', 1 );
//Start av sessions
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'Inloggad';
} else {
$logged = 'utloggad';
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="main.css">
<link rel="shortcut icon" href="logo/wfmini.png">
</head>
<body class="dashboardadmin">
<div class="innehall">
</div>
<p>
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
$pidnew4 = $_POST['pidnew3'];
$inputFileName = 'discussdesk.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$userfName = trim($allDataInSheet[$i]["A"]);
$usereName = trim($allDataInSheet[$i]["B"]);
$userMobile = trim($allDataInSheet[$i]["C"]);
$query = "SELECT name FROM Email_Users WHERE fornamn = '".$userfName."' and efternamn '".$usereName."' and email = '".$userMobile."' and pid = '".$pidnew4."'";
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$existName = $recResult["fornamn"];
if($existName=="") {
$insertTable= mysql_query("insert into Email_Users (fornamn, efternamn, email, pid) values('".$userfName."', '".$usereName."', '".$userMobile."', '".$pidnew4."');");
$msg = 'Record has been added. <div style="Padding:20px 0 0 0;">Go Back to tutorial</div>';
} else {
$msg = 'Record already exist. <div style="Padding:20px 0 0 0;">Go Back to tutorial</div>';
}
}
echo "<div style='font: bold 18px arial,verdana;padding: 45px 0 0 500px;'>".$msg."</div>";
?>
</body>
</html>
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form>
In this form, you mentioned GET method and you are passing variable using GET method in your another page.
You can not get pidnew3 variable to another page because you are using POST method to get pidnew3 variable.
You just need to change the below line from
$pidnew4 = $_POST['pidnew3'];
to
$pidnew4 = $_GET['pidnew3'];
I just realised what can be wrong, you didn't display the $pidnew2 value here
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='$pidnew2'>
<input type="submit" name="submit">
</form>
You should replace that block with
<form method='GET' action='excelimport.php'>
<input type='hidden' name='pidnew3' value='<?php echo $pidnew2; ?>'>
<input type="submit" name="submit">
</form>
Then you get the value of the variable $pidnew2 and not the string '$pidnew2'
You should change the method in the form by POST, as you are trying to get a variable passed through 'GET'. Or as below you can get the variable using the 'GET' method.
$pidnew4 = $_GET['pidnew3'];
Related
hi guys i want to create a zip from the hole files names into my database in my code i can just download just one file but i want to get the hole files from my database into a zip
<html>
<title>Files | github</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.4.1/font/bootstrap-icons.css">
<link href="globe.png" rel="shortcut icon">
<?php
date_default_timezone_set("Asia/Calcutta");
//echo date_default_timezone_get();
?>
<?php
$conn=new PDO('mysql:host=localhost; dbname=github', 'root', '') or die(mysqli_error($conn));
if(isset($_POST['submit'])!=""){
$name=$_FILES['photo']['name'];
$size=$_FILES['photo']['size'];
$type=$_FILES['photo']['type'];
$temp=$_FILES['photo']['tmp_name'];
$date = date('Y-m-d H:i:s');
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"files/".$name);
$query=$conn->query("INSERT INTO upload (name,date) VALUES ('$name','$date')");
if($query){
header("location:index.php");
}
else{
die(mysqli_error($conn));
}
}
?>
<html>
<body>
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" media="screen">
<link rel="stylesheet" type="text/css" href="css/DT_bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/font-awesome.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="font-awesome/css/font-awesome.min.css"/>
<style>
body{
background-color:#24292f;
}
</style>
</head>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" language="javascript" src="js/DT_bootstrap.js"></script>
<?php include('dbcon.php'); ?>
<style>
.table tr th{
border:#eee 1px solid;
position:relative;
#font-family:"Times New Roman", Times, serif;
font-size:12px;
text-transform:uppercase;
}
table tr td{
border:#eee 1px solid;
color:#000;
position:relative;
#font-family:"Times New Roman", Times, serif;
font-size:12px;
text-transform:uppercase;
}
#wb_Form1
{
background-color: #00BFFF;
border: 0px #000 solid;
}
#photo
{
border: 1px #A9A9A9 solid;
background-color: #00BFFF;
color: #fff;
font-family:Arial;
font-size: 20px;
}
</style>
<div class="alert alert-info">
</div>
<!--<table cellpadding="0" cellspacing="0" border="0" class="table table-bordered">
<tr><td><form enctype="multipart/form-data" action="" id="wb_Form1" name="form" method="post">
<input type="file" name="photo" id="photo" required="required"></td>
<td><input type="submit" class="btn btn-danger" value="SUBMIT" name="submit">
</form> <strong>SUBMIT HERE</strong></tr></td></table>
<div class="col-md-18">-->
<div class="container-fluid" style="margin-top:0px;">
<div class = "row">
<div class="panel panel-default">
<div class="panel-body">
<div class="table-responsive">
<form method="post" action="delete.php" >
<table cellpadding="0" cellspacing="0" border="0" class="table table-condensed" id="example">
<thead>
<tr>
<th>ID</th>
<th>FILE NAME</th>
<th>Date</th>
<th>Download</th>
<th>code editor</th>
</tr>
</thead>
<tbody>
<?php
session_start();
$user = $_SESSION["username"];
$project= $_GET['project'];
echo $project;
$query=mysqli_query($conn,"SELECT * FROM project S WHERE date=( SELECT MAX(date) FROM project WHERE pointedname = S.pointedname) and (user='$user' and directoryName ='$project')")or die(mysqli_error($conn));
while($row=mysqli_fetch_array($query)){
$id=$row['user'];
$name=$row['pointedname'];
$date=$row['date'];
$filpath=$row["path"];
?>
<tr>
<td><?php echo $row['user'] ?></td>
<td><?php echo $row['pointedname']; ?></td>
<td><?php echo $row['date'] ?></td>
<td>
<span class="glyphicon glyphicon-paperclip" style="font-size:20px; color:blue"></span>
</td>
<td>
<?php
echo "<a href='../repositories/codeEditorGit/index.php?project=".$row["path"]."'><i class='bi bi-code-slash'></i> ".$row["pointedname"]."</a>";
echo "<a href='zip.php?project=".$row["path"]."'><i class='bi bi-code-slash'></i> ".$row["pointedname"]."</a>"; ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
i tried this code but it didnt work for me
<?php
$conn=new PDO('mysql:host=localhost; dbname=github', 'root', '') or die(mysqli_error($conn));
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $files)
{
$zip->addFile($file_path.$files,$files);
//echo $file_path.$files,$files."<br />";
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
}
session_start();
$user=$_SESSION["username"];
$project = $_GET["project"];
$cqurfetch=mysql_query("SELECT * FROM project where user='$user' and accept='1'");
while($row = mysql_fetch_array($cqurfetch))
{
$file_names[] = $row['user_album_images'];
}
$archive_file_name=time().'.gallery.zip';
$file_path="/uploads/";
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
echo '^^^^^^Zip ended^^^^^^';
?>
also i want to check if the user exist by email but i got an error that when i execute the code he escape the if statment and he go throw executing the insert even the email exist
if(mysqli_num_rows($check_email) > 0){
echo('Email Already exists');
}
code :
$textarea = $_POST["textarea"];
$email = $_POST["email"];
$name = $_POST["name"];
$pswd = $_POST["password"];
$check_email = mysqli_query($conn, "SELECT * FROM sign where email = '$email' ");
if(mysqli_num_rows($check_email) > 0){
echo('Email Already exists');
}
else{
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$result = $sql = "INSERT INTO sign
VALUES ('$email', '$name', '$password','$textarea');
INSERT INTO connected
VALUES ('$email', '')
";
$conn->exec($result);
header("Location: ../image-upload-php-and-mysql-main/index.php");
}
echo('Record Entered Successfully');
}
Hi there i am trying to create a screen in php.
in which i select scenario and the screen displayed accordingly.
but i am stuck in a simple problem that my simple select query is not working
which is
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery) or die("adfasdf");
in same code if change the table name it just work fine, also this table is created in the db as well with the same name i have shared.
here is my complete code.
<?php
include "include/conn.php";
include "include/session.php";
if(isset($_SESSION['logged_user']) && $_SESSION['logged_user'] != '99999'){
header('location: login.php');
}
$query = mysql_query("select curdate() as todayDate");
$show = mysql_fetch_array($query);
if(isset($show)){
$todayDate= $show['todayDate'];
}
$group[] = array();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta Content="no-cache, no-store, must-revalidate" http-Equiv="Cache-Control" />
<meta Content="no-cache" http-Equiv="Pragma" />
<meta Content="0" http-Equiv="Expires" />
<link href="styles/style.css" type="text/css" rel="stylesheet" />
<link href="styles/popupstyle.css" type="text/css" rel="stylesheet" />
<link href="styles/ts.css" type="text/css" rel="stylesheet" />
<link href="styles/calendar.css" type="text/css" rel="stylesheet" />
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
font-size: 11px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body >
</body>
<select id='select_opt'>
<option> Select Assigment </option>
<option value="1"> assign quiz to all Employees </option>
<option value="2"> assign quiz to Sapcific Group </option>
<option value="3"> assign quiz to Sapcific Department </option>
<option value="4"> assign quiz to Sapcific Employee </option>
</select>
<!-- all Users -->
<div id='allUsers' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<select>
<option value=""> select Quiz</option>
</select>
<input type="submit" >
</form>
</div>
<!-- group -->
<div id='group' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>All <input type="checkbox"> </th>
<th>Group Name</th>
<th>Group Code</th>
</tr>
<?php
$group[] = array();
$groupQuery = "Select * from mcb_groups";
$query = mysql_query($groupQuery);
?>
<tr>
<?php if($query){
while($group = mysql_fetch_array($query)){
?>
<td><input type="checkbox" value="<?php echo $group['group_name']; ?>"></td>
<td><?php echo $group['group_name']; ?></td>
<td><?php echo $group['group_code']; ?></td>
</tr>
<?php }
} else{ echo "";} ?>
</table>
</form>
</div>
<!--
####################################
department
####################################
-->
<div id='Department' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>all <input type="checkbox"> </th>
<th>name</th>
<th>code</th>
<th>group</th>
</tr>
<tr>
<?php
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
?>
<td><input type="checkbox"></td>
<td>code</td>
<td>name</td>
<td>group</td>
</tr>
</table>
<input type="submit" >
</form>
</div>
<!--
####################################
Employee
####################################
-->
<div id='employee' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<label>employee id : </label><input type="text" >
<input type="submit" >
</form>
</div>
<script language="javascript" type="text/javascript">
var elem = document.getElementById("select_opt");
elem.onchange = function(){
console.log("yes i am running");
if( document.getElementById("select_opt").value == "1" ){
document.getElementById("allUsers").style.display = "Block";
document.getElementById("group").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "2" ){
document.getElementById("group").style.display = "Block";
document.getElementById("allUsers").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "3" ){
document.getElementById("Department").style.display = "block";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "4" ){
document.getElementById("employee").style.display = "block";
document.getElementById("Department").style.display = "none";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
}
else{
}
};
</script>
</
html>
regard,
Shafee jan
in same code if change the table name it just work fine
Then I would make sure you're connected to the right database. It's surprisingly common for developers to have multiple versions of their database, either on different MySQL instances or else on the same instance under a different schema name. Then they get mixed up, connecting to one database with MySQL Workbench while their app is connecting to a different database.
I would advise that you temporarily add a query to your page to run SHOW TABLES and then dump the result of that query to the log, to confirm that the mcb_department table is present in the database that your PHP script is connected to.
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
Where's your error checking? You need to check the return value of mysql_query() every time you run a query, so if there's a problem, you output the error message to your log. Only this way can you start to solve some of these problems.
$result = mysql_query($deptQuery);
if (!$result) {
trigger_error("Error in file " . __FILE__ . " near line " . __LINE__
. " for query $deptQuery: " . mysql_error());
die("Database error");
}
PS: The advice of some commenters that mysql_* functions are deprecated is true, but probably irrelevant to your question. Folks who focus on the API, when you have said the API is working, are just being pedantic.
I have an input, in which a code is entered and filled the table below with information from mysql optenida, the question is that I want every time a code is entered, the table all the data is added (without deleting the previous ). I got the idea to do with Ajax, but do not know where to start. So you see there is an easier way that I'm not seeing (finding on google). I do not like to add this data to a table, I would like it to be temporarily (until the table is confirmed, will be added to the db).
Any ideas?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table>
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
require ("conectar.php");
$_SESSION["codigo"] = $_POST["input_codigo"];
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
?>
</table>
</body>
</html>
Maybe something like this i write below.
Added jQuery and Ajax request to get the data and then add it to the table.
Changed the PHP a little so that the main HTML is not returned if it is and AJAX request.
Hope it works for you (i didnt test it).
<?php
session_start();
error_reporting(E_ALL ^ E_NOTICE);
$bAjaxRequest = false;
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$bAjaxRequest = true;
}
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) {
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
table {
width:100%;
border: 1px solid black;
border-collapse: collapse;
}
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form action="index.php" method="post" id="frmQuery" name="frmQuery">
<input type="text" name="input_codigo" id="input_codigo" placeholder="Codigo del producto" autocomplete="off" autofocus required><br><br>
</form>
<table id="tblData" name="tblData">
<tr>
<td><b>Codigo</b></td>
<td><b>Descripcion</b></td>
<td><b>Precio</b></td>
<td><b>Cantidad</b></td>
<td><b>Importe</b></td>
</tr>
<?php
} // end if(!$bAjaxRequest) {
// we are always going to return the TR's or ""
require ("conectar.php");
// ALWAYS, BUT ALWAYS VERIFY/VALIDATE USER INPUT!!!
$_SESSION["codigo"] = mysql_real_escape_string($_POST["input_codigo"]); // for example
$sql = "SELECT * FROM $tabla WHERE codigo = ".$_SESSION['codigo']."";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>".$row["codigo"]."</td>
<td>".$row["descripcion"]."</td>
<td>$".$row["venta"]."</td>
<td><input type='number' name='cantidad' value='1' min='1' max='5'></td>
<td>$".$row["venta"]."</td>
</tr>
";
}
} else {
echo "";
}
$conexion->close();
// if not and ajax request deliver the complete HTML
if(!$bAjaxRequest) { ?>
</table>
<script type="text/javascript">
function loadData(codigo) {
$.post( "index.php", { input_codigo: codigo }, function( data ) {
$("#tblData").append(data);
});
}
$(function() {
// jQuery POST are never cached, but if you change to GET you'll need this next line
//$.ajaxSetup ({ cache: false });
$("#frmQuery").submit(function(e) {
e.preventDefault();
loadData($("#input_codigo").val());
});
});
</script>
</body>
</html>
<?php
}
?>
I want to create login and logout session
My table in mysql database is looking like this
CREATE TABLE members (
id int(10) NOT NULL auto_increment,
username varchar(20) NOT NULL,
password varchar(20) NOT NULL, PRIMARY KEY (id) )
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
and mysql connection named as loginproc.php
<?php
// Inialize session
session_start();
// Include database connection settings
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'database'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
/ Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
?>
Then created securedpage.php
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p>Logout</p>
</body>
</html>
index.php
<html>
<head>
</head>
<body>
<form action="loginproc.php" method="post">
UserName:<input type="text" name="user" >
<p> </p>
Password:<input type="password" name="pass" >
<p> </p>
<input type="submit" value=" Login Here " >
<span class="style30">| New?</span>
<a href="signup.php"><span class="style32">Start Here</span>
</form></body></html>
and finally logout page named as logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
Now my problem is when i am entering username and password it will stay only at index.php , it is not going to another page. please see this code and tell me when i am doing wrong.
Thanks.
I have a solution for your problem. You have to bit modify your code as mentioned below -
<?php
// Inialize session
session_start();
//----***Use variabel to capture start time *****------
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
And in logout page add one entry as -
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['username']);
//---****Use end time variable ---------
// Subtract previous start time variable and end time variale
// Delete all session variables
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
Don't use this line
$result=mysql_fetch_array($login);
This will fetch the result into $result as an array, and later own you are using mysql_num_rows() function (which is used for resource , i.e in your case $login)
You the following code
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
You have a problem here:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '". mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
your query will always retrieves 1 row on mysql_num_rows($result) because it retrieves the count of users with the condition, if no one match the username and password, the query retrieves
|count(*)|
+--------+
|0 |
and it is 1 row
I see two problems:
mysql_num_rows takes resource type as parameter. You are passing the result of mysql_fetch_array which can either be an array or FALSE.
You're using deprecated mysql extension. You should be using either MySQLi or PDO for new code.
To fix the mysql_num_rows problem in point 1, use if (mysql_num_rows($login)) {:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($login) == 1) {
index.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password Click here</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logging.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password Click here</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logout.php
<?php
include 'header.php';
include 'footer.php';
session_destroy();
echo "<script>alert('Successfully Logged Out');window.location.href='index.php'</script>";
?>
forgotpass1.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="validateemail1.php" method="POST">
<input type="text" placeholder="Email" name="email"/>
<table width="100%">
<tr><td align="left">
<button type="submit" name="Back" value="Back" onclick="history.go(-1);" >Back</button></td><td>  </td><td align="left"> <button type="submit" name="submit" onclick="return logincheck()">Send Email</button></td></tr></table>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var y = document.frm.email.value;
if(y=="" || y == null){
alert("Enter the Email ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
<?php include 'footer1.php';?>
validateemail1.php
<?php
include 'dbConfig.php';
if (isset($_POST['submit'])){
$email=$_POST['email'];
$n=0;
$query=mysqli_query($con,"SELECT * FROM signup where email ='".$email."'");
while($row=mysqli_fetch_array($query))
{
$db_email=$row['email'];
if($db_email==$email)
{
$n++;
$to=$row['email'];
$subject = "Your Password ";
$txtn = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="1000">
<tr>
<td align="center" bgcolor="#2ce0e8" style="padding: 7px 0 10px 0;background:#f55322 ">
<img src="http://saiss.co.in/supreme_oms/img/oms.png" alt="http://saiss.co.in/supreme_oms/index" width="84" height="36" style="display: block;" />
</td>
</tr>
<td bgcolor="#ffffff" style="padding: 20px 0 30px 0"><center>Hi ,'.$row["username"].'<br>
Your password is: '.$row["password"].'<br> Click to Login</center>
</td>
<tr>
<td bgcolor="#f55322" style="padding: 25px 0px 18px 23px;color: #fff;font-size: 12px;">
© <?php echo date("Y"); ?> OMS All RIGHTS RESERVED.
</td>
<td align="right">
</td>
</tr>
</table>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <OMS>' . "\r\n";
mail($to,$subject,$txtn,$headers);
echo "<script>alert('We Sent Password To Your Email Address');window.location.href='index.php';</script>";
}
}
if($n==0)
{
echo "<script>alert('Your email is Not Matching with our database');window.location.href='index.php';</script>";
}
}
?>
Logging.php
<?php
session_start();
include 'dbConfig.php';
$logname = $_POST['usrname'];
$logpass = $_POST['password'];
if(isset($_POST['usrname'])) {
$name = $_POST['usrname'];
}
if(isset($_POST['password'])) {
$name = $_POST['password'];
}
if($logname != null && trim($logname) !="" && trim($logpass) !="" && $logpass !=null)
{
$getvalue ="";
$sql_query = "Select * from signup where username='".$logname."'and password ='".$logpass."'";
$changepass="";
$result_set = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result_set)==0){
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}else{
while($row=mysqli_fetch_row($result_set))
{
$getvalue = $row[0];
$changepass = $row[3];
}
$_SESSION["usrnam"] = $getvalue;
if($changepass=="Y"){
echo "<script>window.location.href='changepassword.php'</script>";
}else
{
echo "<script>window.location.href='dashboard.php'</script>";
}
}
}else{
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}
?>
what is going on?
I recently installed and updated a site template , and designed it.
My friend had some site which he got on it a php login form, for users to log in.
I asked him for the code and he gave me it, and ofc I just copied the code and pasted it between my site template code.
I know u confused, so here's the deal:
This is a basic page on my site:
<?php
include('config.php');
if(MODULE == 'none')
{
include(LOVE_ROOT . '/system/love_head.php');
$content = '<h2> Welcome to OUR SITE </h2>
<br />
Hey this is a test
<br />
Hey this is a test
<br />
Hey this is a test
<br /> <br />
Hey this is a test
<br />
Hey this is a test
<br />
Hey this is a test
<br />
Hey this is a test
<br />
Hey this is a test
<br /> <br />
Welcome
<br />
Welcome to our site
<br />
Hey this is a test
<br /> <br /> <br />
';
include(LOVE_ROOT . '/system/love_foot.php');
}
else
{
header('Location: modules/' . MODULE);
}
?>
and here is the login form php code:
<?php
ob_start();
?>
<html dir="rtl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255" />
<style>
a:link,a:visited,a:active
{
background: transparent;
color: #000000;
text-decoration: none;
}
a:hover
{
background: transparent;
color: #00dfff;
}
td {
border: 1px solid gray;
padding: 5px;
text-align: center;
}
</style>
</head>
<center>
<?php
include('mysql.php');
$fname = $_POST['fname'];
$password = $_POST['pass'];
$pass1 = md5($password);
$pass = sha1($pass1);
$select = mysql_query("SELECT * FROM `users` WHERE fname='$fname'");
$cu = mysql_fetch_array($select);
if (!empty($_COOKIE['adv_U']) AND !empty($_COOKIE['adv_P']))
{
echo "אתה כבר מחובר לתחרות.";
}
else
{
if (!empty($username) || !empty($password))
{
if (empty($cu))
{
?>
<font color="darkred"><b>
שגיאה - השם הפרטי שהכנסת לא קיים במערכת
</b></font>
<br><br>
<input type="button" value="חזור אחורה" onclick="window.location.href='javascript:window.history.back(-1)';">
<?php
}
else if ($pass == $cu['password'])
{
if ($cu['ban'] == 1)
{
echo "<font color='red'><b>אתה מורחק מהתחרות עקב עבירה על החוקים!</b></font><br>אתה מוחזר לדף הבית של המערכת...";
echo "<meta http-equiv='refresh' content='3; url=index.php'>";
}
else
{
setcookie('adv_U',$fname);
setcookie('adv_P',$pass);
header( 'Location: index.php' );
}
}
else
{
?>
<font color="darkred"><b>
הסיסמא שהכנסת שגויה
</b></font>
<br><br>
<input type="button" value="חזור אחורה" onclick="window.location.href='javascript:window.history.back(-1)';">
<?php
}
}
else
{
?>
<form method="post" action="login.php">
<table>
<tr><td>שם פרטי</td><td><input type="text" name="fname"></td></tr>
<tr><td>סיסמא</td><td><input type="password" name="pass"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="התחברות"></td></tr>
<tr><td colspan="2" align="center"><font size="2">(עוד לא נרשמת?)</font></td></tr>
</table>
</form>
<?php
}
}
?>
</div>
</td>
</tr>
</table>
</body>
</html>
<?php
ob_end_flush();
?>
I tried to copy the php code between the headers of my page, to something like that:
<?php
include('config.php');
if(MODULE == 'none')
{
include(LOVE_ROOT . '/system/love_head.php');
$content = '<h2> Welcome to OUR SITE </h2>
<br />
<?php
ob_start();
?>
<html dir="rtl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255" />
<style>
a:link,a:visited,a:active
{
background: transparent;
color: #000000;
text-decoration: none;
}
a:hover
{
background: transparent;
color: #00dfff;
}
td {
border: 1px solid gray;
padding: 5px;
text-align: center;
}
</style>
</head>
<center>
<?php
include('mysql.php');
$fname = $_POST['fname'];
$password = $_POST['pass'];
$pass1 = md5($password);
$pass = sha1($pass1);
$select = mysql_query("SELECT * FROM `users` WHERE fname='$fname'");
$cu = mysql_fetch_array($select);
if (!empty($_COOKIE['adv_U']) AND !empty($_COOKIE['adv_P']))
{
echo "אתה כבר מחובר לתחרות.";
}
else
{
if (!empty($username) || !empty($password))
{
if (empty($cu))
{
?>
<font color="darkred"><b>
שגיאה - השם הפרטי שהכנסת לא קיים במערכת
</b></font>
<br><br>
<input type="button" value="חזור אחורה" onclick="window.location.href='javascript:window.history.back(-1)';">
<?php
}
else if ($pass == $cu['password'])
{
if ($cu['ban'] == 1)
{
echo "<font color='red'><b>אתה מורחק מהתחרות עקב עבירה על החוקים!</b></font><br>אתה מוחזר לדף הבית של המערכת...";
echo "<meta http-equiv='refresh' content='3; url=index.php'>";
}
else
{
setcookie('adv_U',$fname);
setcookie('adv_P',$pass);
header( 'Location: index.php' );
}
}
else
{
?>
<font color="darkred"><b>
הסיסמא שהכנסת שגויה
</b></font>
<br><br>
<input type="button" value="חזור אחורה" onclick="window.location.href='javascript:window.history.back(-1)';">
<?php
}
}
else
{
?>
<form method="post" action="login.php">
<table>
<tr><td>שם פרטי</td><td><input type="text" name="fname"></td></tr>
<tr><td>סיסמא</td><td><input type="password" name="pass"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="התחברות"></td></tr>
<tr><td colspan="2" align="center"><font size="2">(עוד לא נרשמת?)</font></td></tr>
</table>
</form>
<?php
}
}
?>
</div>
</td>
</tr>
</table>
</body>
</html>
<?php
ob_end_flush();
?>
<br /> <br /> <br />
';
include(LOVE_ROOT . '/system/love_foot.php');
}
else
{
header('Location: modules/' . MODULE);
}
?>
Of course I handled all the problems, deleted php tags where it's not neccessery, closed qoutes and etc..
but still.. it just won't work.
Sorry for my English,
Sorry for my lame knowledge,
please try and help a bummed guy who stuck with this problem already a week..
Thanks alot!
ALSO(!) I tried to fix it with NetBeans... but didn't manage.. lol I dont evenk now how this software works..
If I take the php code as it self, the original one, it works. If I take the original index file without anything else, it works.
When I add the code to the site template with the "love_foot" "love_head" and etc.. around the php login code, it tells me "unexpected T String".
So what is the problem here?
Thanks alot , I am so LOST right now!
You're missing the semicolon on Line 8. That's causing the rest of the PHP lines to be ignored.
Change it to:
$content = '<h2> Welcome to OUR SITE </h2><br />';
And around line ~127, you forgot to open the <? tag.
I believe that should fix the errors.
However you should use an IDE with syntax highlighting. That'll help you debug code faster.