Unable to insert data into database using PHP and J Query Mobile - php

I can insert data into the database for the several time before this. I'm using web matrix and XAMPP to develop. I have problem while dealing with ports but then after altering something it become okay, but the database does not receive data anymore. My other system using PHP that was been develop is running good but the problem is with the jQuery mobile.
This is the index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header" data-position="fixed">
<h3>
Student Uitm
</h3>
</div>
<div data-role="content">
<form action="http://localhost/student/save2db.php" method="post">
<label>Nama</label><input type="text" name="Nama">
<label>No Kad Pengenalan</label><input type="text" maxlength="12" name="icno">
<label>Jantina</label><select name="jantina">
<option value="L">Lelaki</option>
<option value="P">Perempuan</option>
</select>
<input name="sbt" type="submit" value="save" data-inline="true">
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>
Footer
</h3>
</div>
</div>
</body>
</html>
and this is the save2db.php file:
<?php
$con=mysqli_connect("localhost","root"," ","student");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO student1 (Nama, icno, jantina)
VALUES
('$_POST[Nama]','$_POST[icno]','$_POST[jantina]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>

The problems:
you check for the db connection, but you let the script run through even when it's failed
you are not being cautious enough with the received data
you don't log errors
internal problem symptoms leak out to users
Here's a possible alternative to your script taking care of these issues:
<?php
$con = mysqli_connect("localhost","root"," ","student");
// Check connection
if (mysqli_connect_errno()) {
trigger_error("Failed to connect to MySQL: " . mysqli_connect_error(),
E_USER_ERROR);
die("unable to complete request");
} else if (!(isset($_POST['Nama']) &&
isset($_POST['icno']) && isset($_POST['jantina'])) {
trigger_error( "incomplete POST data", E_USER_ERROR);
die("unable to complete request");
} else {
$nama = mysqli_real_escape_string($con, $_POST['Nama']);
$icno = mysqli_real_escape_string($con $_POST['icno']);
$jantina = mysqli_real_escape_string($con,$_POST['jantina']);
$sql = "INSERT INTO student1 (Nama, icno, jantina) VALUES ('$nama','$icno','$jantina')";
if (!mysqli_query($con,$sql)) {
trigger_error("query failed :" . mysqli_error($con), E_USER_ERROR);
die("unable to complete request");
}
echo "1 record added";
mysqli_close($con);
}
With the above modification done, check the php logs after unsuccessful updates to know the possible reasons of the failure.

Related

PHP Form does not log in and move to next page

I ran into another problem with my website that I can't get around.
I'm trying to make it so when the admin logs in he will be taken to the admin page but for some reason when I enter the correct details into the log in and press the submit button it just brings me back to the admin log in page again.
Here is a Gyazo of my problem
https://gyazo.com/34f133fea4b20ec285ee7ff491053145
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>
<link href='https://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/148866/reset.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<body>
<main id="cd-main-content">
<section id="cd-intro">
<h1>Admin Log In</h1>
<header class="cd-header">
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$adminusername = stripslashes($_REQUEST['adminusername']);
//escapes special characters in a string
$adminusername = mysqli_real_escape_string($con,$adminusername);
$adminpassword = stripslashes($_REQUEST['adminpassword']);
$adminpassword = mysqli_real_escape_string($con,$adminpassword);
//Checking is user existing in the database or not
$query = "SELECT * FROM `admin` WHERE username='$adminusername'
and password='".md5($adminpassword)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $adminusername;
// Redirect user to admin page /////////////////////////////////////////////////////////////////////
header("Location: adminpage.php");
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='admin.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<form action="" method="post" name="login">
<input type="text" name="adminusername" placeholder="Username" required />
<input type="password" name="adminpassword" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
<a class="cd-menu-trigger" href="#main-nav">Menu<span></span></a>
</header>
<div class="cd-blurred-bg"></div>
</section> <!-- cd-intro -->
</main>
<div class="cd-shadow-layer"></div>
<nav id="main-nav">
<ul>
<li><span>Login</span></li>
<li><span>What's On</span></li>
<li><span>Favourites</span></li>
<li><span>About</span></li>
<li><span>Admin</span></li>
</ul>
Close<span></span>
</nav>
</body>
<script src='js/jquery.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
You are doing:
if (isset($_POST['username'])) {
//...
}
Try this
if (isset($_POST['adminusername'])) {
//...
}
As a note, I suggest you to try use a framework, like laravel.
first I would debug by var_dump($_POST) and see what you get. I would bet that since you dont have an ID set for the input value name it is not working. If anything checking for ISSET($_POST['username']) would never work because you do not have a vairable set for that name.
var_dump($_POST) and see what you get. If not add an ID='username' to the input
try this :-
if (isset($_POST['submit'])){
// rest of code...
}

jQuery Mobile form post issues, PHP warning: (expects parameter 1 to be mysqli, null given)

home.html file:
Two simple jQ Mobile pages with a header and fixed footers. The form is on page one. I haven't added any stipulations like "password must match confirm password" for now. I just want to get it working with the DB first i.e. store in DB.
<!DOCTYPE html>
<html>
<head>
<!-- Include meta tag to ensure proper rendering and touch zooming -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include jQuery Mobile stylesheets -->
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<link rel="stylesheet" type="text/css" href="https://example.net/Login/styles.css">
<!-- Include the jQuery library -->
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Include the your Ajax-ify file -->
<script type="text/javascript" src="https://example.net/Login/functions.js"></script>
<!-- Include the jQuery Mobile library -->
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<!-- -->
<!-- Page One starts here -->
<!-- -->
<div data-role="page" id="pageone">
<div data-role="header" data-theme="b">
<h1>Welcome</h1>
</div>
<div data-role="main" class="ui-content">
<br>
<br>
<!-- Form starts here -->
<form id="NewForm" method="post" action="include.php">
<label>Username</label>
<input type="text" name="username" placeholder="E.g. JoeB95">
<br>
<label>Email</label>
<input type="text" name="email" placeholder="E.g. Joe#email.com">
<br>
<label>Password</label>
<input type="password" name="password_1" placeholder="E.g. 8969-545a-r3">
<br>
<!--Submit button goes below here -->
<div id="register"><input type="submit" name="register" data-inline="true" value="Submit"></div>
</form>
<br>
<p>Already a member?</p> Sign In
<br>
<span id="result"></span>
<br>
</div>
<div data-role="footer" id="foot" data-position="fixed" data-theme="b">
<h1>footer</h1>
</div>
</div>
<!-- Page One ends here -->
<!-- -->
<!-- Page Two starts here -->
<div data-role="page" id="pagetwo">
<div data-role="header" data-theme="b">
<h1>Welcome</h1>
</div>
<div data-role="main" class="ui-content">
<br>
<br>
<p>Not a member?</p> Signup
<br>
</div>
<div data-role="footer" id="foot" data-position="fixed" data-theme="b">
<h1>footer</h1>
</div>
</div>
functions.js file: (Ajax-ify)
Code for Ajax-ifying the form is below. I'm not sure if any errors exist here.
// AJAX-ify the form
$(document).on("pagecreate","#pageone",function()
{
$("#register").click( function() {
$.post( $("#NewForm").attr("action"),
$("#NewForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#NewForm").submit( function() {
return false;
});
});
db.php file:
This code does work, as it connects with the DB and I've used it before.
<?php
//put your connection code here
$servername = 'localhost';
$username = 'admin_example';
$password = '123456-7';
$dbname = 'example_DB';
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully, <br>";
?>
include.php file:
This is where I believe the issues are. In the error_log, it points to lines 8 and 11 as the problem areas;
PHP Warning: mysqli_query() expects parameter 1 to be mysqli, null given in public_html/Login/include.php on line 8
PHP Warning: mysqli_error() expects parameter 1 to be mysqli, null given in public_html/Login/include.php on line 11
I know there are similar topics regarding these errors, but I couldn't relate it directly to mine. Can anyone suggest what the problem is and what needs to be changed? Thanks.
<?php
$user = $_POST['username'];
$email = $_POST['email'];
$password_1 = $_POST['password_1'];
$access = md5($password_1);
$sql = "INSERT INTO users (`username`, `email`, `password`) VALUES ('$username', '$email', '$password_1')";
if(mysqli_query($conn,$sql)){
echo "Successfully Inserted";
} else {
echo ("Error description: " . mysqli_error($conn));
}
?>
The home.html file calls include.php via the form action. However, include.php does not call the db.php file. It appears you're missing something like:
require db.php;
in your include.php file. Without it the $conn variable set in db.php on line 10 is not visible in the include.php file. That is causing the error.

Very strange situation with Can't connect to local MySQL server

I'm experiencing a strange situation, and it's the first time in 5 years...
my code:
<?php include("static/inc/settings.php"); ?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>News</title>
<link rel="stylesheet" href="static/css/style.css" media="screen" />
<script type="text/javascript" src="static/js/jquery.js"></script>
<script type="text/javascript" src="static/js/tinymce.min.js"></script>
<script type="text/javascript" src="static/js/script.js"></script>
</head>
<body>
<div id="master">
<?php if(isset($_POST["inserisci"])){
$tipo=$_POST["tipo"];
$titolo=$_POST["titolo"];
$testo=$_POST["testo"];
$link=$_POST["link"];
$info=pathinfo($_FILES["immagine"]["name"]);
$ext=$info["extension"];
$newname=md5($titolo.time()).".".$ext;
$target="static/uploads/".$newname;
move_uploaded_file($_FILES['immagine']['tmp_name'],$target);
mysql_query("INSERT INTO links(url) VALUES('".$link."');") or die(mysql_error()); ?>
<div class="inserito scompari">La news รจ stata inserita</div>
<?php } ?>
<div id="header">
<?php include("static/inc/menu.php"); ?>
</div>
<div id="main">
<div class="block">
<form enctype="multipart/form-data" id="inserisci_news" method="post">
<p>Tipo<br /><select name="tipo" id="tipo"><option value=""></option><option value="sinistra">sinistra</option><option value="sopra">sopra</option></select></p>
<p>Titolo<br /><input type="text" name="titolo" id="titolo" value="ciao" /></p>
<p>Testo<br /><textarea name="testo" id="testo">prova</textarea></p>
<p>Link<br /><input type="text" name="link" id="link" value="http://www.google.it" /></p>
<p>Immagine<br /><input type="file" name="immagine" value="" /></p>
<input type="submit" name="inserisci" value="Inserisci" />
</form>
</div>
</div>
</div>
</body>
</html>
basically, when I compile the form, I get an error in the query: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
but if I remove the if(isset($_POST["inserisci"])){ cycle.... It goes!!!
What the hell?
In settings.php there's the connection:
<?php $dbname="xxx";
$user="xxx";
$pswd="xxx";
$host="xxx";
if(!isset($link)){
$link=mysql_connect($host, $user, $pswd);
if(!$link){
die('Could not connect: '.mysql_error());
}
mysql_set_charset('utf8', $link);
$db_selected=mysql_select_db($dbname, $link);
if(!$db_selected){
die('Could not use db: '.mysql_error());
}
}
date_default_timezone_set('Europe/Rome'); ?>
I think the problem is that you're doing everything with global variables and you've stomped on yourself.
The relevant line in settings.php:
$link=mysql_connect($host, $user, $pswd);
The relevant line in your code:
$link=$_POST["link"];
What you have done is overwritten the variable containing the MySQL connection with something else. This is probably resulting in your query not having a valid connection object to use. I don't know why removing the isset() conditional appears to cause the error to disappear, but I would recommend changing the name of either of these variables and seeing what happens.

Conflict with my php form and jquery mobile js

I'm currently using jQuery Mobile for my project. In my login page, I need to get the username and the password that the user input but every time i'm going to click the login button, it will display nothing. But when i tried to remove the cdn from jQuery mobile it works well, but the design is different.
Here's my code for my login page:
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<!--CDN FROM JQUERY MOBILE-->
<meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8">
<link rel="stylesheet" href="jquery.mobile-1.4.5.css">
<script src="jquery-1.11.2.js"></script>
<script src="jquery.mobile-1.4.5.js"></script>
<!--END-->
<title>Inhand Pinagkaisahan</title>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h1>Inhand Pinagkaisahan</h1>
</div>
<div data-role="main" class="ui-content">
<form method="post" action="get.php">
<input type="text" name="uname" placeholder="Username" />
<input type="password" name="pword" placeholder="Password" />
<center><input type="submit">Login</center>
<center>Forgot Password</center>
<center><p>No account? Sign up or Learn more.</p></center>
</form>
</div>
<div data-role="footer">
<h1></h1>
</div>
</div>
</div>
</body>
</html>
I'm receiving this error:
Notice: Undefined index: uname in C:\xampp\htdocs\InhandPinagkaisahan\get.php on line 6
Notice: Undefined index: pword in C:\xampp\htdocs\InhandPinagkaisahan\get.php on line 7
And here is my php:
<?php
$con=mysql_connect('localhost','root','ADMIN') or die(mysql_error());
mysql_select_db('inhand') or die("cannot select DB");
<!--This is the part not is not working when ever i'm going to use the cdn, but when i comment out the cdn, it works properly.-->
$uname=$_POST['uname'];
$pword=$_POST['pword'];
<!--END-->
$query=mysql_query("SELECT * FROM user WHERE uname='$uname' AND pword='$pword'");
$numrows=mysql_num_rows($query);
if($numrows!=0)
{
while($row=mysql_fetch_assoc($query))
{
$dbusername=$row['uname'];
$dbpassword=$row['pword'];
}
if($uname == $dbusername && $pword == $dbpassword)
{
session_start();
$_SESSION['sess_user']=$uname;
/* Redirect browser */
header("Location: newsfeed.php");
} else {
echo "Invalid username or password!";
}
}
?>

how can i show echo result in same page of submiting form using ajax

i made this simple code to update the database row, and i want to show the result of all the echo statement in the same page of the submit form without reloading the page (using ajax).
Form HTML code:
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Update Status</title>
</head>
<body>
<form method="POST" action="update.php">
<p>Order ID: <input type="text" name="T1" size="5" required></p>
<p>Status: <select size="1" name="D1">
<option selected value="In Progresss">In Progresss</option>
<option value="Finished">Finished</option>
</select></p>
<p><input type="submit" value="Update" name="B1"></p>
</form>
</body>
</html>
update.php file:
<html>
<head>
<title>Update Status</title>
<?php
$connection = new mysqli("localhost","root","T00r", "sells");
// Check connection
if($connection->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;;
}
//select database to use
$db_select = mysqli_select_db($connection,"sells");
if(!$db_select){
die("Database selection failed: " . mysqli_error());
}
$T1=$_POST['T1']; $D1=$_POST['D1'];
//check if Order ID is available
$check1=mysqli_query($connection,"SELECT Order_ID FROM clients WHERE Order_ID = '$T1' ");
if (mysqli_num_rows($check1) == 0) {
echo " <b> == No Order With This ID == </b>";
}
else {
//insert value into database
$sql=mysqli_query($connection,"UPDATE Clients SET Status = '$D1' WHERE Order_ID = '$T1'");
//check if the Status is Updated
$check2=mysqli_query($connection,"SELECT Status FROM clients WHERE Order_ID = '$T1' ");
//get the value of Satuts to check if it's equal to the input data
while($row = mysqli_fetch_array($check2)){
if($row["Status"] != $D1){
echo " <b> == Status Not Updated == </b>";
}
else echo"<b> == Status Updated == </b>";
}
if(!$sql){
die("Database query failed: " . mysqli_error());
}
}
mysqli_close($connection);
?>
</head>
</html>
True, you should use AJAX. It's not that hard, try this:
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Update Status</title>
</head>
<body>
<form method="POST" id="updateForm" action="update.php">
<p>Order ID: <input type="text" name="T1" size="5" required></p>
<p>Status: <select size="1" name="D1">
<option selected value="In Progresss">In Progresss</option>
<option value="Finished">Finished</option>
</select></p>
<p><input type="submit" value="Update" name="B1"></p>
</form>
<div id="ajaxResponse"></div>
<!-- Include the JQuery library !-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
<!-- Add a listener. This will be invoked when the form is submitted, 'submit' is the action, and '#updateForm' is the context it is listening !-->
$(document).on('submit','#updateForm',function(e){
<!-- This stops the original event. So that's the original submit action of the form. !-->
e.preventDefault();
<!-- Get the form data and serialize it into an array. !-->
var data = $('#updateForm').serializeArray();
<!-- The AJAX request. '.post' indicates that it should be a POST request. 'data' add the serialized array in the POST request. 'htmlResponse' is the response you get from the POST request, in your case your echo rules. !-->
$.post('update.php',data,function(htmlResponse){
<!-- The POST request is finished and the response is putted in the htmlResponse variable. So display this by setting the content(html) of the ajaxResponse div to the htmlResponse variable
$('#ajaxResponse').html(htmlResponse);
});
});
</script>
</form>
</body>
</html>

Categories