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.
Related
I'm currently having an issue where my query returns a success however there is no actual update that occurs when I check my SQL database. Oddly enough, when I copy the same exact query into phpMyAdmin, a response is successfully returned and the query works just fine, the rows are updated. (Note: I'm well aware of the high risk of SQL injection, however mysqli_escape_string isn't working for some reason so I'll worry about that when I go into the production stage.)
script.php
$fave = json_decode($_POST['af']);
$unfave = json_decode($_POST['uf']);
$fave = "'".implode("','", $fave)."'";
$unfave = "'".implode("','", $unfave)."'";
if ($fave !== "''"){
$fq = "UPDATE post SET fave='1' WHERE 'an_id' IN ($fave) AND bid='$bizusr' AND fave='0'";
$r_fq = mysqli_query($GLOBALS["___mysqli_ston"], $fq);
$ar_fq = mysqli_affected_rows($GLOBALS["___mysqli_ston"]);
} else {
$r_fq = 1;
$ar_fq = 0;
}
if ($unfave !== "''"){
$ufq = "UPDATE post SET fave='0' WHERE 'an_id' IN ($unfave) AND bid='$bizusr' AND fave='1'";
$r_ufq = mysqli_query($GLOBALS["___mysqli_ston"], $ufq);
$ar_ufq = mysqli_affected_rows($GLOBALS["___mysqli_ston"]);
} else {
$r_ufq = 1;
$ar_ufq = 0;
}
if ($r_fq && $r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "Favourites have been updated successfully. You've added $ar_fq favorites and removed $ar_ufq favorites." ));
die($output);
}
if (!$r_fq && $r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "We've successfully favorited $ar_fq links, however there was an issue in unfavoriting some links, try refreshing." ));
die($output);
}
if ($r_fq && !$r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "We've successfully unfavorited $ar_ufq links, however there was an issue in favoriting some links, try refreshing." ));
die($output);
}
if (!$r_fq && !$r_ufq){
$output = json_encode(array('type'=>'error', 'text' => "There was an error in updating your favorited links." ));
die($output);
}
// $un = mysqli_prepare($GLOBALS["___mysqli_ston"], "UPDATE analytics SET fave='0' WHERE an_id IN (?) AND bid= ? AND fave='1'");
// $fa = mysqli_prepare($GLOBALS["___mysqli_ston"], "UPDATE analytics SET fave='1' WHERE an_id IN (?) AND bid= ? AND fave='0'");
// mysqli_stmt_bind_param($un, 'ss', $unfave, $blockject);
// $a = mysqli_stmt_execute($un);
// mysqli_stmt_close($un);
// mysqli_stmt_bind_param($fa, 'ss', $fave, $blockject);
// $b = mysqli_stmt_execute($fa);
// mysqli_stmt_close($fa);
The variables $fave and $unfave would return values like so: 'abcd123','dcba321','hello123', which would make the query look like so:
UPDATE post SET fave='0' WHERE 'an_id' IN ('abcd123','dcba321','hello123') AND bid='$bizusr' AND fave='1';
Now, entering the query into phpMyAdmin works just fine, but when doing it through php, the response returns a success however no rows are actually updated, so I'm not sure what is going on as my php error.log is as clean as a whistle.
Also, if you're wondering what my require_once connection.php file looks like which connects me to the database, it is the following:
$link = ($GLOBALS["___mysqli_ston"] = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD));
if(!$link) {
die('Failed to connect to server: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
//Select database
$db = ((bool)mysqli_query($GLOBALS["___mysqli_ston"], "USE " . constant('DB_DATABASE')));
if(!$db) {
die("Unable to select database");
}
Silly me, I'm not sure why it was returning a successful query, however wrapping the column id an_id in single quotes was the issue
I have this code is working fine my application gets the data with json and is all fine but when I insert special characters like ñ which I need to get I can't have been told that I should use the utf8_encode but I just don't know how to apply it here since.
<?php
require_once(dirname(__FILE__).'/ConnectionInfo.php');
//Set up our connection
$connectionInfo = new ConnectionInfo();
$connectionInfo->GetConnection();
if (!$connectionInfo->conn)
{
//Connection failed
echo 'No Connection';
}
else
{
if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
{
$mod = $_POST['mod'];
$lec = $_POST['lec'];
$clase = $_POST['clase'];
//Create query to retrieve all contacts
$query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
$params = array($mod,$lec,$clase);
$stmt = sqlsrv_query($connectionInfo->conn, $query,$params);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$contacts = array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
"lbl_variable_pregunta" => $row['PreguntaEjercicio'],
"opcion1" => $row['Opcion1Ejercicio'],
"opcion2" => $row['Opcion2Ejercicio'],
"opcion3" => $row['Opcion3Ejercicio'],
"opcion4" => $row['Opcion4Ejercicio'],
"EstaCorrecta" => $row['EstaCorrectaEjercicio']
);
//Add the contact to the contacts array
array_push($contacts, $contact);
}
//Echo out the contacts array in JSON format
echo json_encode($contacts);
sqlsrv_close($connectionInfo->conn);
}
}
sqlsrv_close($connectionInfo->conn);
}
sqlsrv_close($connectionInfo->conn);
?>
If your issue lies with pushing non-latin characters to MySQL then you might just have to configure your database to use UTF8. There are good tutorials online that show you how to do that.
I'm building a simple sign up form with AngularJS and sending the data to a PHP page using JQuery's $.post(). When I send the data, it correctly gets inserted into the database. However, the returned json that I am logging is showing my data fields as null.
Console:
{"status":"success","email":null,"id":null,"sessionId":null}
Javascript:
$.post("admin/addUser.php", {
email: form.email,
password: form.password
}).done(function(data){
console.log(data);
});
PHP:
$email = mysql_real_escape_string($_POST["email"]);
$password = md5(mysql_real_escape_string($_POST["password"]));
$sessionId = md5(uniqid(microtime()) . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT']);
//Add this user to the database
$sql = mysql_query("INSERT INTO users (email, password, sessionId) VALUES ('".$email."', '".$password."', '".$sessionId."')");
if ($sql){
//Now find the user we just added
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."'");
if ($getUser){
$row = mysql_fetch_array($getUser);
$user = array(
'status' => 'success',
'email' => $row['email'],
'id' => $row['id'],
'sessionId' => $row['sessionId']
);
echo json_encode($user);
}else{
$user = array(
'error' => mysql_error()
);
echo json_encode($user);
}
}else{
$user = array(
'error' => mysql_error()
);
echo json_encode($user);
}
Are you sure that you have only one record in here
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."'");
Try to dump $row and see the response. BTW I would suggest you to add limit
$getUser = mysql_query("SELECT * FROM users WHERE email = '".$email."' AND sessionId = '".$sessionId."' LIMIT 1");
Ok, I dug around and found the answer to this. It was a mistake on my end. I was only storing the password and sessionId as varchar(30). When I was generating the sessionId and checking it against the DB, it was being cut off when it was stored, since I was only allowing 30 chars. I update to 255 and works as expected :-P.
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);
}
I am creating a login based application and this is what I have so far. I am trying to read each field into a separate textarea. I have tried to bind the data etc. I do get a output in the textarea, but it prints all the fields in one textarea. Please help.
<?php
selectDB();
function selectDB() {
$usertoken = $_POST['usertoken'];
//Database service vars
$databasehost = "localhost";
$databasename = "morerandom";
$databasetable = "random";
$databaseusername = "root";
$databasepassword = "root";
$con = mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT username, useremail, firstname, lastname FROM $databasetable WHERE usertoken='$usertoken'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if ($count)
{
$rows = array();
while ($row = mysql_fetch_object($result)) {
$rows[] = $row;
}
echo $rows[0]->username . "\n";
echo "\n";
echo $rows[0]->useremail . "\n";
echo $rows[0]->firstname . "\n";
$first = $rows[0]->lastname;
echo $first;
// echo "$lastname;"
}
else
{
echo 'Token not valid';
}
mysql_free_result($result);
mysql_close($con);
}
?>
What you are getting is just one string. There are better way to retrieve this kind of data from the server side(XML or AMF).
If you want to go ahead with your method then split the string using '\n' as a delimiter but check first that the server response is not 'Token not valid'.
So something like this should work:
First remove the echo "\n"; line under the echo $rows[0]->username . "\n";
var responseArray:Array = theStringResult.split('\n');
So now the responseArray stores the username at position 0, useremail at position 1, firstname at position 2 and lastname at position 3.
But again, you are sending data from the server as raw text and this is not the best way to do it. Check this link to see how this can be done using AMFPHP.