php output json - php

I'm trying to make it easy for me to request json output using jquery from php/mysql. Right now I'm using the below. Can anyone recommend a better way??
/do.php?username=bob
<?php
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
if($countUser[0] < 1){
return array('username' => 'false');
}else{
return array('username' => 'true');
}
$db->disconnectDB();
}
?>
I get back a clean {'username':'false'} or {'username':'true'} which works for what I need; but is there a better way in PHP to do this?
Wow - amazing answers! I dumped my old db class and replaced it with:
<?php
function db_connect(){
$dbh = new PDO("mysql:host=localhost;dbname=thisdb", "dbuser", "dbpass");
return ($dbh);
}
?>
Then in my do.php script I made this change:
<?php
if(isset($_GET['username'])){
header('content-type: application/json; charset=UTF-8');
echo json_encode(checkUserName($_GET['username']));
}
function checkUserName($v){
$dbh = db_connect();
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", addslashes($v));
if($count = $dbh->query($sql)){
if($count->fetchColumn() > 0){
return array('username'=>true);
}else{
return array('username'=>false);
}
}
}
?>
and my jquery is:
function checkUserName(str){
$.getJSON('actions/do.php?username=' + str, function(data){
var json = data;
if(json.username == true){
// allowed to save username
}else{
// not allowed to save username
}
});
}

$str = $_SERVER['QUERY_STRING'];
if($str != ''){
if(preg_match("/username/",$str)){
parse_str($str);
$json = json_encode(checkUserName($username));
echo $json;
}
}
This can be written so much easier by using $_GET superglobal:
if (isset($_GET['username'])) {
echo json_encode(checkUserName($_GET['username']));
}
Inside checkUserName():
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
You should escape $v properly:
$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", mysql_real_escape_string($v));
$findUsername = mysql_query($sql);
Better yet, learn PDO / mysqli and use prepared statements.
$db->disconnectDB();
Unless you're using persistent connections, you don't need this statements. If you do, you should keep the return value inside a variable first and only return after the disconnect.

I don't know what's your DB class, but this looks prettier.
<?php
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
$countUser = mysql_fetch_row($findUsername);
$db->disconnectDB(); // no code after "return" will do effect
return ($countUser[0] != 0); // returning a BOOL true is better than a string "true"
}
// use addslashes to prevent sql injection, and use isset to handle $_GET variables.
$username = isset($_GET['username']) ? addslashes($_GET['username']) : '';
// the above line is equal to:
// if(isset($_GET['username'])){
// $username = addslashes($_GET['username']);
// }else{
// $username = '';
// }
echo json_encode(checkUserName($username));
?>

By your way, If you want to process the json data in jquery you can do like this
$.ajax({
type:"POST",
data:'username=bob',
url: "do.php",
success: function(jsonData){
var jsonArray = eval('(' + jsonData + ')');
if(jsonArray.username == 'true'){
// some action here
}else if((jsonArray.username == 'false')){
// someother action hera
}
}
},"json");

If you want a fix just replace your checkUsername function with this one:
function checkUserName($v){
$db = new DB();
$db->connectDB();
$findUsername = mysql_query("SELECT username FROM user WHERE username = '$v' LIMIT 1");
if(mysql_num_rows($findUsername))
return array('username' => mysql_result($findUsername,0));
else
return array('username' => 'false');
}
Or a simplier way:
if(isset($_GET['username'])){
$db = new DB();
$db->connectDB();
$query = mysql_query(sprintf("SELECT username FROM user
WHERE username='%s'",
mysql_real_escape_string($_GET['username'])
);
if(mysql_num_rows($query))
$json = array('username'=>mysql_result($query,0));
else
$json = array('username'=>false);
header('content-type:application/json');
echo json_encode($json);
}

Related

why i cant get the json from this scrip in php using alamofire?

i wrote this script to sign in the user in PHP in order to save the data to the server, if the user has been created the scrip should return a simple json with true or false.
<?php
require "../private/autoload.php";
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] == "POST") {
print_r($_POST);
$Error = "";
$staff = $_POST['staff_ID'];
$email = $_POST['email'];
$pass = $_POST['password'];
$name = $_POST['Name'];
$cpt = $_POST['isCPT'];
$date = date("Y-m-d H:i:s",time()); // date of creation
// check if user alrady exixt
$sqlexixst = "SELECT * FROM `users` WHERE staff_ID = ?";
$st = $pdo->prepare($sqlexixst);
$st->execute(array($staff));
$result = $st->fetchAll();
if (count($result) > 0){
$array = array(
"user_created"=>false
);
$js = json_encode($array);
echo $js;
} else {
// user not exixt creo utente
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex,$email)){
// ok email
if (is_numeric($staff)){
// ok id
$sql = "INSERT INTO users (staff_ID,password,email,isCPT,Name, date) VALUES (?,?,?,?,?,?)";
$statement = $pdo->prepare($sql);
$statement ->execute([$staff,$pass,$email,$cpt,$name,$date]);
$array = array(
"user_created"=>true,
"staff_ID"=>$staff
);
$js = json_encode($array);
echo $js;
}
}else{
$Error = "pls enter valid email";
echo $Error;
}
}
}else {
echo 'no post';
}
?>
i'm sending the request using Alamofire... if i post the request using respondeString i can see the corret print out of the json, if i use respondJSON i cant get the json print out.. i get error say 'JSON could not be serialized. thata could not be read because it isn't in the correct format'
Alamofire and swiftyjson code:
func nxTest (){
let parm : [String : Any] = ["staff_ID": "3879","password":"12345678","email":"damiano.miai#gmail.com", "isCPT":false,"Name":"Marco Frizzi"]
AF.request("http://192.168.50.10/nx/public/register.php", method: .post, parameters: parm,headers: nil, interceptor: nil, requestModifier: nil).validate()
.responseJSON { js in
switch js.result {
case .success(let value) :
let json = JSON(value)
debugPrint(json)
case .failure(let err) :
debugPrint(err.localizedDescription)
}
}
.responseString { st in
print(st)
}
}

Php unable to determine userid availability with jQuery Validate

I have a problem with using jQuery validate remote function with php. I try to check the user id with query whether the user id is exist or not. But it alway show user is in used.
Here is my jQuery validate code:
userID: {
required: true,
minlength: 5,
remote : {
url: "checkUserId.php",
type: "post"
}
},
Here is my php checking code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_POST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$result = sqlsrv_query($conn,$query);
$row_count = sqlsrv_num_rows($result);
if($row_count === false){
echo 'false';
}
else if($row_count >=0){
echo 'true';
}
?>
Anything I did wrong in my query?
Change your if else condition.
if($row_count == 0){
echo 'true';
}else{
echo 'false';
}
true = not exist, false = exist
I had successfully solved it with this code. Thanks for all the support.
Here is my updated code:
<?php
include "session.php";
include 'dbConnect.php';
global $conn;
$requestedID = $_REQUEST['userID'];
$query = "SELECT * FROM Users WHERE _userID = '$requestedID'";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result = sqlsrv_query($conn,$query , $params, $options);
$row_count = sqlsrv_num_rows($result);
if($row_count >= 1){
echo 'false';
}
else{
echo 'true';
}
?>

Php code does not send query to database

I am trying to update my database using ajax, but I cannot seem to understand why the php code does not update the database. The script:
function Insert () {
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST","list_insert.php");
XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
var returnedData = XMLHttpRequestObject.responseText;
var messageDiv = document.getElementById('messageDiv');
messageDiv.innerHTML = returnedData;
}
}
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
var data = item + '|' + desc + '|';
XMLHttpRequestObject.send("data=" + data);
}
return false;
}
This is the php code for list_insert:
<?php
include "function_list.php";
$myData = $_POST['data'];
$datetime = date('Y-m-d H:i:s');
list($items,$description) = explode ('|',$myData);
$statement = "INSERT INTO record ";
$statement .= "(items,description) ";
$statement .= "VALUES (";
$statement .= "'".$items."', '".$description."')";
print $statement;
insert($statement);
print "done";
?>
My php function to insert into the db (function_list):
<?php
$con=mysqli_connect("localhost","shop");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function insert($statement) {
global $con;
mysqli_query($con,$statement);
}
?>
When I print the statement out, the query is correct (I have verified this by manually copy pasting it in mysql). I think the issue is with my insert function.
Any help is appreciated,
thank you.
Firstly, all mysql statements must end in a semicolon.
Secondly, have you made sure $items and $description are the values you expect them to have? Do they have any unescaped quotes?
Also, typically you would send each of the fields as a separate value like so:
var item = document.getElementById('items').value;
var desc = document.getElementById('description').value;
XMLHttpRequestObject.send("items=" + item + "&desc=" + desc);
$$items = $_POST['items'];
$description = $_POST['desc'];
By default, the username for mysql is root, and the password is blank, even though you aren't prompted for these, they are set by default.
I think this might be the issue
in ur global variable $con letz say you put this
$con = new mysqli("host", "user", "pwd", "dbname");
then
function insert($statement) {
$con->query($statement);
$con->close();
}

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

PHP get data from jquery

Im trying to write a simple prgram that the server can get data from client.
I write a simple code in my script
var str = "testString";
$.post("http://anonymous.comze.com/test1.php", { string: str });
in the server,
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3',$var)";
$result2= mysql_query($sql2,$conn);
The question is var is always null. The sql2 can be executed if I change $var into "1111" for example,
but if I put $var, it doesn't work. Can anyone give some advice?
your are passing string to the query so it should be
$var = $_POST['string']; // this fetches your post action
$sql2 = "INSERT INTO afb_comments VALUES ('3','".$var."')";
$result2= mysql_query($sql2,$conn);
please also check datatype of the that column.
Use this example and learn from this code how to get data
Or
use can also use this link:
http://api.jquery.com/jQuery.get/
$user and $pass should be set to your MySql User's username and password.
I'd use something like this:
JS
success: function(data){
if(data.status === 1){
sr = data.rows;
}else{
// db query failed, use data.message to get error message
}
}
PHP:
<?php
$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";
$con = mysql_pconnect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid = $_GET["pid"];
if(empty($pid)){
echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
} else{
if (!$dbs){
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));
}
else{
//connection successful
$sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
$result = mysql_query($sql) or die(mysql_error());//execute SQL string command
if(mysql_num_rows($result) > 0){
$rows = mysql_fetch_row($result);
echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
}else{
echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));
}
}
}
?>
As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters, Part Number => part_number.

Categories