I'm trying to send some Data to a MySQL Database that I have stored on a server. When I press the submit button, my PHP scripts let me know that the connection to the DB has been successful, but the insertion of data has not. I can't find any issue in the Error logs, or an obvious problem when I examine the code via Google Chrome's developer tools.
Below is the HTML File;
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="http://example.com/JS/functions.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
//CSS
<style>
.ui-page {
background: #4990E2;
}
p {
color: #ffffff;
}
</style>
</head>
div data-role="page" id="page1">
<div data-role="header" data-theme="a">
<h1>Welcome</h1>
</div>
<!-- Main page content goes under this line -->
<div data-role="main" class="ui-content">
<br>
<br>
<br>
<form id="myForm" method="post" action="include.php">
<label for="rating">How are you feeling?</label>
<input type="range" name="rating" id="rating" value="50" min="0" max="100" data-popup-enabled="true">
<input id="submit" type="submit" data-inline="true" value="Submit">
</form>
<br>
<br>
<span id="result"></span>
<br>
<p>Some text</p>
</div>
<div data-role="footer" data-position="fixed" data-theme="b">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Example</li>
<li>Example</li>
<li>Example</li>
</ul>
</div>
</div>
</div>
<!-- Page ends here -->
<!-- -->
Below is the PHP file (db.php);
<?php
//put your connection code here
$servername = 'localhost';
$username = 'user_admin';
$password = '12345-678';
$dbname = 'my_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>";
?>
Below is the PHP file(include.php);
<?php
include 'db.php';
$rating = $_POST['rating'];
$sql="INSERT INTO user Values('$rating')";
if(mysqli_query($conn,$sql)){
echo "Successfully Inserted";
} else {
echo "Did NOT insert";
}
?>
Below is the Javascript file (functions.js);
// AJAX-ify the slider
$(document).on("pagecreate","#page1",function()
{
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#myForm").submit( function() {
return false;
});
});
The MySQL table is called 'user' and the column is called 'rating'. The column is set as int(3) [this should match with the slider max value of 100?].
Can anyone pinpoint why the Data isn't being inserted into the DB?
change this
$sql="INSERT INTO user Values('$rating')";
to this
$sql="INSERT INTO user (`rating`) VALUES ('$rating')";
rating would be the column name for that field in the db, if the table has more than one column then the statement need to say in which column it need to be placed.
also to show errors of the statement use this
if(mysqli_query($conn,$sql) or die(msqli_error($conn))){
... your code here > it worked
}else{
... your code here > it failed
}
Related
Just started working with php and little bit struggling with jQuery. Went through documentation and in my opinion everything should be working fine, however no. The hidden value does not appear visible after entering the wrong data into form. In css I assigned to #warning display:none
index.php
<?php require "../src/models/Database.php"; ?>
<?php include_once "../src/controllers/DatabaseController.php"; ?>
<?php session_start(); ?>
<?php include "../src/includes/header.php"; ?>
<?php
if (isset($_POST["submit"])) {
$username = $_POST["username"];
$password = $_POST["password"];
$dbController = new DatabaseController();
$dbController->loginUser($username, $password);
}
?>
<div class="container main">
<h1 class="text-center">Web</h1>
<p class="text-center" id="warning">Incorrect username or password</p>
<div class="row login-page">
<form class="form" method="POST">
<input class="form-control" type="text" name="username" placeholder="Username" required>
<input class="form-control" type="password" name="password" placeholder="Password" required>
<input class="btn btn-success" type="submit" name="submit" value="Login">
</form>
</div>
</div>
<?php include "../src/includes/footer.php"; ?>
header.php
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Bootstrap starts -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Bootstrap ends -->
<!-- Css starts -->
<link rel="stylesheet" href="../src/styles/css/main.css">
<!-- Css ends -->
<!-- Jquery starts -->
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<!-- Jquery ends -->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="title"></title>
</head>
<body>
databasecontroller.php
<?php
class DatabaseController extends Database
{
public function loginUser($username, $password)
{
$connection = $this->connection;
$escapedUsername = mysqli_real_escape_string($connection, $username);
$escapedPassword = mysqli_real_escape_string($connection, $password);
$query = "SELECT * FROM users WHERE username = '$escapedUsername'";
$result = $this->findUser($query, $escapedPassword);
if ($result) {
// $_SESSION["authenticated"] = true;
echo "Logged in";
} else { ?>
<script>
$("#warning").show();
</script>
<?php
}
}
}
composer.json
{
"require": {
"components/jquery": "^3.5"
}
}
You are including the jQuery script before the html is finished.
Therefore, there is no #warning on the page, yet. Nothing is shown.
You should either include your script after the <p class="text-center" id="warning"> or you can tell jQuery to wait until the document is ready before applying the show():
$( document ).ready(function() {
$("#warning").show();
});
I am trying to do a post request using angular and getting the response as the html code of index.html. I am using zurb's foundation for apps.
<!doctype html>
<html lang="en" ng-app="application">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation for Apps</title>
<link href="./assets/css/app.css" rel="stylesheet" type="text/css">
<script src="./assets/js/foundation.js"></script>
<script src="./assets/js/templates.js"></script>
<script src="./assets/js/routes.js"></script>
<script src="./assets/js/app.js"></script>
</head>
<body>
<div class="grid-frame vertical">
<div class="grid-content shrink" style="padding: 0;">
<ul class="primary condense menu-bar">
<li><a><strong>opt1</strong></a></li>
<li><a ui-sref="pros"><strong>opt2</strong></a></li>
</ul>
</div>
<div ui-view class="grid-content" >
</div>
</div>
</div>
</body>
</html>
home.html is by set as root so it will be displaying a login form
<form ng-controller="LoginController as login" ng-submit="login.loginProcess()">
<div class="grid-block">
<div class="grid-content">
<input type="text" name="username" ng-model="login.user.username">
</div>
<div class="grid-content">
<input type="password" name="password" ng-model="login.user.password">
</div>
<div class="grid-content">
<input type="submit" value="submit">
</div>
</div>
</form>
This is my app.js file
(function() {
'use strict';
var application = angular.module('application', [
'ui.router',
'ngAnimate',
//foundation
'foundation',
'foundation.dynamicRouting',
'foundation.dynamicRouting.animations'
])
.config(config)
.run(run)
;
config.$inject = ['$urlRouterProvider', '$locationProvider'];
function config($urlProvider, $locationProvider) {
$urlProvider.otherwise('/');
$locationProvider.html5Mode({
enabled:false,
requireBase: false
});
$locationProvider.hashPrefix('!');
}
function run() {
FastClick.attach(document.body);
};
application.controller('LoginController',['$scope','$http',function($scope,$http){
this.user = {};
this.loginProcess = function(){
console.log(JSON.stringify(this.user));
var postData = JSON.stringify(this.user);
var config = {method: 'POST', url: '/login.php', data:postData};
$http(config)
.success(function(data, status, headers, config) {
console.log(data);
})
.error(function(data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
});
};
}]);
})();
Now as soon as i submit the form I am able to fetch the data properly from the form but it is not being posted properly since the html code of index.html is being displayed in the console when the success function runs.Please suggest a solution so that i will be able to fetch the data from the php file.
<?php
echo $_REQUEST['username'];
?>
and its not working even if I use
file_get_contents("php://input");
In login.php write your php code before any html code starts and add a die() before any html code starts.
login.php
<?php
/*
php code to login
*/
die();
?>
<html>
....
</html>
For the life of me I can't figure out why the following code is not working. I'm quite inexperienced so any assistance appreciated.
I want to get a simple connection working where an ajax call will return a username from a mySQL DB (this is a precursor to a much larger project). My HTML file is the following:
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="jquery/test-theme.min.css"/>
<link href="jquery/jquery.mobile.icons.min.css" rel="stylesheet" />
<link href="jquery/jquery.mobile.structure-1.4.5.min.css" rel="stylesheet" />
<link href="jquery/app.css" rel="stylesheet" />
<script src="jquery/jquery-2.1.4.min.js"></script>
<script src="jquery/jquery.mobile-1.4.5.min.js"></script>
<script> function login(){
$(document).ready(function(){
var user = $("#username")[0].value;
var email = $("#email")[0].value;
$.ajax({
type: "GET",
url: "http://localhost:8888/test/connection.php",
data: "username="+user+"&email="+email,
success: function(result){
if(result){
$("#message")[0].value = "Success" +result;
}
else{
$("#message")[0].value = "Fail :(";
}
},
error: function(result){
$("#message")[0].value = "Ajax error!"+result;
}
});
});
}
</script>
</head>
<body>
<div data-role="page">
<div data-role="header" data-theme="c">
<h1>Sign Up!</h1>
</div><!-- /header -->
<div role="main" class="ui-content">
<h3>Sign Up</h3>
<label for="txt-first-name">Username</label>
<input type="text" name="txt-first-name" id="username" value="" onkeyup="login()">
<label for="txt-email">Email Address</label>
<input type="text" name="txt-email" id="email" value="" onkeyup="login()">
<input type="text" id="message"></input>
<button id="submit" onclick="login()"> Submit</button>
<div data-role="popup" id="dlg-sign-up-sent" data-dismissible="false" style="max-width:400px;">
</div>
</div><!-- /content -->
</div>
</body>
</html>
And my PHP:
<?php
$user = $_REQUEST['username'];
$email = $_REQUEST['email'];
mysql_connect("localhost:8889","root","root") or die(mysql_error());
mysql_select_db("TEST") or die(mysql_error());
$result = mysql_query("SELECT username, email FROM login WHERE username ='$user'");
while($row = mysql_fetch_array($result)){
if($user = $row["username"]){
echo $row["id"];
}
else{
echo "failed getting user"
}
}
?>
I have a DB called TEST running via MAMP with some entries in the login table for username and email. I just want to get the connection running properly but I'm stumped.
I'm developing a jquery mobile app that uses php to get information from the database ( e.g user login ). but I've this problem: I need to display specific information from the database depends on the user logged ( clients and proyects are related one each other by 'project' field in clients and 'id' in projects )
I was trying to add the field 'project' into the 'login' query but when I made this the app couldn't logged
Thanks in advance for your help
----------- index.html --------------
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="theme/css/jquery.mobile.min.css" />
<link rel="stylesheet" href="theme/css/surinteractive.min.css" />
<link rel="stylesheet" href="theme/css/jquery.mobile.icons.min.css" />
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.js"></script>
<script src="js/json.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="a">
<header data-role="header" data-position="fixed">
<h1>Sistema de gestión de Requerimientos</h1>
</header>
<div data-role="content">
<div id="fm">
<form id="form">
<label for="username">User:</label>
<input type="text" value="" name="username" id="username"/>
<label for="password">Pass:</label>
<input type="password" value="" name="password" id="password"/>
<a data-role="button" id="login-button" data-theme="a" class="ui-btn-icon-right ui-icon-plus ui-btn-b">
Sign in
</a>
</form>
</div>
</div>
<footer data-role="footer" data-position="fixed" id="footer">
<p>© Copyright 2014 </p>
</footer>
</div>
<div data-role="page" id="menu" data-theme="a">
<header data-role="header" data-position="fixed">
Back
<h3>Bugs List</h3>
</header>
<div data-role="content">
<h3>Welcome: </h3>
<ul data-role="listview" data-inset="true">
<li>Create a bug</li>
<li>Create an enhacement</li>
</ul>
</div>
<footer data-role="footer" data-position="fixed" id="footer">
<p>© Copyright 2014</p>
</footer>
</div>
</body>
</html>
------------------ json.js --------------------------
$(document).on('pagebeforeshow', '#login', function(){
$('#login-button').on('click', function(){
if($('#username').val().length > 0 && $('#password').val().length > 0){
userObject.username = $('#username').val();
userObject.password = $('#password').val();
var outputJSON = JSON.stringify(userObject);
ajax.sendRequest({action : 'login', outputJSON : outputJSON});
} else {
alert('Please fill all requested information');
}
});
});
var ajax = {
sendRequest:function(save_data){
var address = null;
//address = 'http://127.0.0.1/app/inc/userValidation.php?jsoncallback=?';
$.ajax({url: address,
crossDomain: true,
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show', {theme:"a", text:"Initializing...", textonly:true, textVisible: true});
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide');
},
success: function (result) {
if(result == "true") {
$.mobile.changePage( "#menu", { transition: "slide"} );
} else {
alert('Invalid login. Please try again!'); // In case result is false throw an error
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Connection error, please try again');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
username : "",
password : ""
}
------------ userValidation.php -------------------
<?php
$jsonObject = json_decode($_REQUEST['outputJSON']); // Decode JSON object into readable PHP object
$username = $jsonObject->{'username'}; // Get username from object
$password = $jsonObject->{'password'}; // Get password from object
$connection = null;
$connection = new mysqli('127.0.0.1', 'xxxx', 'xxxx', 'xxxx');
$query = "SELECT * FROM clients WHERE username = '".$username."' and password = '".$password."'";
$result = mysqli_query($connection,$query);
$num = mysqli_affected_rows($connection);
if($num != 0) {
echo "true";
} else {
echo "false";
}
?>
Database ( Structure & Relationship )
clients
id, name, username, password, projectid, status, creation_date
projects
id, project, description, technologies, status, creation_date
bugs
id name projectid, type, environment,description, status, creation_date
projectid.clients = id.projects
id.projects = projectid.bugs
Objective: Store the username in a global variable to be recovered in another page
Finally I've solved this issue creating a new schema called sessions, when the user signs it to the app, it will be store in that schema. After this, if the user wants to get the list of bugs created a new sql sentence will be called to join 'sessions' in that search
I found this link which works with jquery but not with jquery-mobile multiselect
Link to other post
Any ideas where i might be going wrong. As soon as i add multiple="multiple" i get no results showing. Also if i have it missing i dont get the jquery mobile theme but i do get my list populated
html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<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="css/logout-button.min.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.min.css" />
<link rel="stylesheet" href="css/my.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</script>
<script src="js/jquery.mobile-1.3.0.min.js"></script>
<script src="js/jquery.cookies.2.2.0.min.js"></script>
</head>
<body>
<div data-role="page" id="index4">
<div data-theme="a" data-role="header">
<a data-role="button" data-direction="reverse" data-rel="back" data-transition="slide"
data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<h3>
Event Details
</h3>
</div>
<div data-role="content">
<form id="eventForm" name="eventForm">
<div data-role="fieldcontain">
<script type="text/javascript">
$(document).on("pagebeforeshow", "#index4", function() {
$(function(){
var items="";
$.getJSON("event-details.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.email+"'>"+item.username+"</option>";
});
$("#a1_title").html(items);
$("#a1_title").trigger("change");
});
});
});
</script>
<select id="a1_title" multiple="multiple">
</select>
</div>
<div data-role="fieldcontain">
<label for="manual">Add Emails</label>
<textarea cols="40" rows="8" name="emails" id="emails"></textarea>
</div>
<input type="submit" value="Submit" id="submitEventButton">
</form>
</div>
</div>
</body>
</html>
my php
require_once("../backend/functions.php");
dbconn();
$id = $CURUSER["id"];
$res = "SELECT email,username FROM users left join cal_contacts on cal_contacts.contactid = users.id WHERE cal_contacts.userid = $id";
$res1 = mysql_query($res);
$data = array();
while($row = mysql_fetch_array($res1))
{
$data[] = $row;
}
echo json_encode($data);
jQuery Mobile is a little bit different the a classic multiple select box.
You didn't do anything wrong, you were lacking one additional attribute. Without it jQuery Mobile multiple select can't be created successfully.
Additional needed attribute is this one:
data-native-menu="false"
Working example: http://jsfiddle.net/Gajotres/dEXac/
$(document).on('pagebeforeshow', '#index', function(){
// Add a new select element
$('<select>').attr({'name':'select-choice-1','id':'select-choice-1','multiple':'multiple', 'data-native-menu':'false'}).appendTo('[data-role="content"]');
$('<option>').html('Select option!').appendTo('#select-choice-1');
$('<option>').attr({'value':'1'}).html('Value 1').appendTo('#select-choice-1');
$('<option>').attr({'value':'2'}).html('Value 2').appendTo('#select-choice-1');
// Enhance new select element
$('select').selectmenu();
});
One more thing, you don't need to use:
$("#a1_title").trigger("change");
It is a overkill in your case, you only need to enhance one dynamic select, do it like this:
$('select').selectmenu();
To find out more take a look at my other article: jQuery Mobile: Markup Enhancement of dynamically added content