I am making a web application which allows user to get funds for the project,I have got most part working but I am stuck at one place where the php script returns a positive status code but no data gets inserted into Mysql database. Following is the php script i am using:
Code:
<?php
session_start();
if(!isset($_SESSION['username']))
{
echo "Unauthorised Page Usage Please Relogin to Access All the Page features;";
header('location:login.html');
}
$sponsor=mysql_real_escape_string($_POST['sponsorid']);
$projectid=mysql_real_escape_string($_POST['projectid']);
$pledge=mysql_real_escape_string($_POST['pledgevalue']);
$servername = "localhost";
$usernam = "root";
$password = "";
$dbname = "project";
$httpStatusCode = 400;
$httpStatusMsg = 'Incorrect Username or Password';
$protocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
$connection=new mysqli($servername,$usernam,$password,$dbname);
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
$sql1="INSERT INTO `sponsor`(`spon_id`,`project_id`,`spon_amt`,`spon_date_time`) VALUES ('$sponsor','$projectid','$pledge',NOW())";
$result=$connection->query($sql1);
if ($result) {
$Success=200;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$result);
}
else {
$Success=400;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$httpStatusMsg);
}
?>
Below is the ajax used to post data to a page:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if(this.status===404){
alert(this.responseText);
}
if(this.status===200)
{
alert("Project backed successfully");
window.location.reload(true);
}
}
};
xhttp.open("POST", "sponsor.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param= "sponsorid"+"="+ <?php echo json_encode($_SESSION['username']); ?>+"&"+"pledgevalue"+"="+document.getElementById("pledge").value+"&"+"projectid"+"="+<?php echo json_encode($projectid);?>;
console.log(param);
xhttp.send(param);
}
I have cross referenced my sponsor table to make sure that every field is same.The code works fine on my friend`s computer. Please help me
Update: the $sql1 query is giving me Error code:1644 Problem when I ran it in Database (using XAMMP).
Please help.
Change
$result=$connection->query($sql);
To
$result=$connection->query($sql1);
You have used $sql1 as a query and when you fire query to database you are using $sql which is not available actually.
If make error reporting ON you will see an error about undefined variable $sql
If still it is not solve then print generated sql query using echo $sql1; and try it executing in database.you will get exact error.
Try this:
<?php
session_start();
if(!isset($_SESSION['username']))
{
echo "Unauthorised Page Usage Please Relogin to Access All the Page features;";
header('location:login.html');
}
$sponsor=mysql_real_escape_string($_POST['sponsorid']);
$projectid=mysql_real_escape_string($_POST['projectid']);
$pledge=mysql_real_escape_string($_POST['pledgevalue']);
$servername = "localhost";
$usernam = "root";
$password = "";
$dbname = "project";
$httpStatusCode = 400;
$httpStatusMsg = 'Incorrect Username or Password';
$protocol=isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
$connection=new mysqli($servername,$usernam,$password,$dbname);
if (!$connection) {
die("Connection failed: " . $connection->connect_error);
}
$sql1="INSERT INTO `sponsor`(`spon_id`,`project_id`,`spon_amt`,`spon_date_time`) VALUES ('$sponsor','$projectid','$pledge',NOW())";
$result=$connection->query($sql1);
if ($result) {
$Success=200;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$result);
}
else {
$Success=400;
$httpStatusMsg=mysqli_error($connection);
header($protocol.' '.$Success.' '.$httpStatusMsg);
}
?>
Related
How to update a status from database if status is empty in using php? I have this condition in php. I have this if condition that decides if $getstatus is empty it will update from database to Avail. I tried refreshing the page after querying the database. But it will not update in database. Is there anyway to update this without using form submit in php?
<?php
session_start();
include "includes/connection.php";
// Display all parking slots
$sql = $connection->prepare('SELECT * FROM parkingslot where parkingslotid = 1');
$sql->execute(); // execute query
$result = $sql->get_result(); // fetch result
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$getstatus = $row["status"];
echo $getstatus;
}
}
if (empty($getstatus)) {
$sql = $connection->prepare("UPDATE parkingslot SET status = 'Avail' where parkingslotid = 1 ");
}
?>
Codes in connection for connecting to database
connection.php
<?php
$server = "localhost";
$username = "root";
$password = "";
// create connection
$connection = mysqli_connect($server,$username,$password);
// check connection
if(!$connection)
{
die("No connection found." . mysqli_connect_error());
}
else {
// select a database
$select_db = mysqli_select_db($connection,'smartparkingsystem');
if(!$select_db)
{
$sql = 'CREATE DATABASE sample';
// create database if no db found
if(mysqli_query($connection,$sql)) {
echo "Database Created";
}
else {
echo "Database not found" . mysqli_connect_error() . '\n';
}
}
else {
// Database already existed
// do nothing...
}
}
?>
If I understand your goal of: For row(s) whereparkingslotid=1 - Update status to 'Avail' but only if status is not currently set, this might help:
<?php
session_start();
include "includes/connection.php";
$connection->prepare("UPDATE `parkingslot` SET `status`=? WHERE `parkingslotid`=? AND (`status` IS NULL OR `status`=?)");
$connection->bind_param("sis", $status, $parkingslotid, $empty_str);
$status = 'Avail';
$parkingslotid = 1;
$empty_str = '';
$connection->execute();
echo $connection->affected_rows.' rows affected';
$connection->close();
?>
This saves a bit of processing by not checking with PHP first.
You can use this query:
"UPDATE parkingslot SET status = 'Avail' where status IS NULL OR status = '' "
Edited:
#lumonald gave the right anwser in the comment. You're not executing your second SQL statement.
I am trying to input data to MySQL using PHP. Don't know what's wrong. The connection succeeds, no errors but at the end there is not data being written to the database.
$dbhost = "localhost";
$dbname = "listings";
$un = $_POST["un"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$des = $_POST["des"];
$quan = $_POST["quantity"];
$specs = $_POST["specs"];
$price = $_POST["price"];
$url1 = ".";
$url2 = ".";
$url3 = ".";
$url4 = ".";
$connection = mysqli_connect($dbhost,$un,$pass,$dbname);
if (!$connection) {
die("Error".mysqli_error);
} else {
echo "Database connection successfull ".$des;
}
$query = "INSERT INTO items
(name,description,quantity,specs,price,url1,url2,url3,url4) VALUES
'$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')
";
echo "Hellos";
$exeute_query = mysqli_query($query,$connection);
if(!execute_query){
die("error ".mysqli_error());
echo "query error";
} else {
echo "Query successfull";
}
mysqli_close($connection);
Any help?
There are several small mistakes in your code:
$query = "INSERT INTO items (name,description,quantity,specs,price,url1,url2,url3,url4) VALUES ('$name','$des','$quan','$specs','$price','$url1','$url2','$url3','$url4')";
echo "Hellos";
**$exeute_query** = mysqli_query($query,$connection); // $execute_query instead of $exeute_query
if(!**execute_query**){ //$execute_query instead of execute_query
die("error ".mysqli_error());
echo "query error";
}
else{echo "Query successfull";}
mysqli_close($connection);
?>
Your code breaks at the if statement because no fucntion with that name is found (if you do not use the dollarsign to show it is a variable, php will interpret it as a function. Also, when initiating your variable you forgot a 'c' so make sure to check if you have the correct variable name or php won't find your variable. Now your query will work or give an error message in case of wrong data formats or bad connection. Use code listed below to debug your php in the future.
error_reporting(E_ALL);
ini_set('display_errors', 'On');
Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.
What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.
The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"
Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.
MySQL Tables:
Users Example:
cols: username | password | email | classcode | tcode | genralauth |
hello | world | hello.world#gmail.com | 374568536 | somthin | 8945784953 |
Tokens Example:
cols: gauth | tk |
3946893485 |wr8ugj5ne24utb|
PHP:
<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {
echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);
if ($conn->query($sql2) === TRUE) {
echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
$correct = TRUE;
}
else {
$correct = FALSE;
}
?>
<?php
if ($correct === TRUE) {
$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
$result3 = $conn->query($sql3);
}
?>
<?php
if ($correct === TRUE) {
$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";
if ($conn->query($sql4) === TRUE) {
echo "New token genrated.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<?php
if ($correct === TRUE) { ?>
<p>Succesfuly loged in!</p><br/>
<button>Continue</button><br/>
<?php
}
elseif ($correct === FALSE) { ?>
<p>Incorrect, please try again.</p><br/>
<button>Back</button><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;
}
$conn->close();
?>
This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.
PHP:
<html>
<h1 class="title">Virtual Work Sheets!</h1>
<p class="h_option">[Log In / Register]</p><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);
?>
<?php
if (!$_GET['tk'] == $data) {
echo "
<p>Invalid token, please consider re-logging.</p>
";
}
else {
?>
<?php
switch ($_GET['view']) {
case teacher:
?>
Teacher page html here...
<?php
break;
case student:
?>
Student page html here...
<?php
break;
default:
echo "Please login to view this page.";
}
}?>
</html>
I suggest that you change your approach.
Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.
First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Now, see how we use it on the Index (and Restricted) pages?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
More about AJAX - study the simple examples
I can't seem to find a way to block my page from being accessed. I have a page to give tickets to users in mysql, but you can simply type it into http to receive tickets, how do i stop people from doing that??
<html>
<head>
<?php
header("refresh:33;url=tickets_give.php" );
?>
<link rel="stylesheet" href="finessecss.css">
</head>
<body bgcolor="#F9F9F9" background="background3.jpg">
<div class="videobox">
<div class="video"><p>Video Player Unavailable At This Moment</p></div>
<div class="clockbox">
<span id="countdown" class="timer"></span>
<script>
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown')[0].innerHTML = "";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
</div>
</div>
</body>
</html>
There is my code for my video page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users_database";
session_start();
$name = $_SESSION['name'];
$pass = $_SESSION['pass'];
if (!(isset($_SESSION['can_accesss']) && $_SESSION['name'] != '')) {
Header("Location:welcome_get.php");
}
unset($_SESSION['can_access']);
// rest of page code
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ('$access' == 'Finesseshopisthebest'){
;
}
else{
echo'mysql' or die;
}
$sql = "UPDATE users_database SET tickets=tickets+10 WHERE username= '$name' and password= '$pass'";
if (mysqli_query($conn, $sql)) {
Header("Location:tickets.php");
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</body>
</html>
And that is my give tickets page. How do i stop people from going straight to tickets_give.php?
If you're looking for a 20-second solution, just check for the presence of a precise query string, eg yoursite.com/somepage?foo=bar. If $_GET["foo"] is not set, call exit and forget about it.
Warning: this is security through obscurity; anyone with a network monitor or even just shoulder surfing would breeze past this, but I guess it's better than nothing. Clearly a smarter, long-term solution is to add meaningful authentication, but it sounds like you have a very short-term problem you need to solve!
Hi I am facing a unique issue with my PHP script.Here is my code. After writeToDB() is executed I dont see the echo ("<script> top.location.href=www.facebook.com</script>");
Can someone let me know why my script stops executing after writing to db?
<?php
function writeToDB($access_token,$uid,$username,$birthday,$gender,$age)
{
/* Database Connection */
$user = "xxxx";
$password = "xxxx";
$host = "xxxxxxxxxxxxxxxxxx";
//connect to database, where tsnames.ora is setup
$connect_obj = oci_connect($user, $password, $host);
if ($connect_obj) {
error_log("connected okay");
} else {
$err = OCIError();
echo "Oracle connection error " . $err[text];
return;
}
$select_query = "SELECT USER_ID FROM FBTABLE WHERE USER_ID= '$uid'";
$select_sql_stmt = oci_parse($connect_obj, $select_query);
//execute statement
try {
$r = oci_execute($select_sql_stmt, OCI_DEFAULT);
if (!$r) {
$p = oci_error($select_sql_stmt);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
$user_id_in_db = null;
while (oci_fetch($select_sql_stmt)) {
$user_id_in_db = oci_result($select_sql_stmt, 'USER_ID');
}
// User already exists in db so update instead of insert
if ($user_id_in_db != null) {
$query ="UPDATE FBTABLE SET ACCESS_TOKEN='$access_token' WHERE USER_ID='$uid'";
} else {
$query = "INSERT INTO FBTABLE(ACCESS_TOKEN, USER_ID,USER_NAME,BIRTHDAY,GENDER,AGE)
VALUES
('$access_token','$uid','$username','$birthday','$gender','$age')";
}
//create sql statement
$sql_statement = oci_parse($connect_obj, $query);
//execute statement
try {
$r = oci_execute($sql_statement, OCI_DEFAULT);
if (!$r) {
$p = oci_error($sql_statement);
echo "Oci Execute error";
}
} catch (Exception $e) {
echo "<br>Failed to get database info" . $e->getMessage();
}
//Commit transaction
$committed = oci_commit($connect_obj);
//Test whether commit was successful. If error occurred, return error message
if (!$committed) {
$error = oci_error($conn);
echo 'Commit failed. Oracle reports: ' . $error['message'];
}
//close the connection
$oci_free_statement($sql_statement);
if (oci_close($connect_obj)) {
echo " oci connection not closed!!!";
}
//close the connection
$oci_free_statement($sql_statement);
}
?>
<html>
<body>
<?php
$access_token = $_GET['access_token'];
$uid = $_GET['uid'];
$username = $_GET['username'];
$birthday = $_GET['birthday'];
$gender = $_GET['gender'];
$age = $_GET['age'];
echo $username;
writeToDB($access_token,$uid,$username,$birthday,$gender,$age);
echo ("<script> top.location.href=www.facebook.com</script>");
?>
</body>
</html>
i think error is in $oci_free_statement($sql_statement); must be oci_free_statement($sql_statement); extra $ before oci_free_statement
http://php.net/manual/en/function.oci-free-statement.php
no any error show because of error_display is off
Your JavaScript code should be
echo ("<script> top.location.href='http://www.facebook.com';</script>");
It's happen because writeToDB() causes error. You don't see this error because error_display is off or error_reporting = 0
Also maybe you didn't install OCI8. So when you call oci_connect it will cause error.
Thanks.
you are not using quotes around the string:
www.facebook.com should be 'www.facebook.com'