I am generating my MYSQL update statement dynamically in PHP. As I want my application to be secure to SQL injections I want to use the prepared statement function. But as I'm pretty experienced I'm struggling to do so. Below my code so far:
function sqlUpdate($tablename)
{
$connect = sqlConnect();
$updateString = "UPDATE " . $tablename . " SET ";
$columnname = getColumnname($tablename, false, true);
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
if ($k+1 < count($columnname, COUNT_RECURSIVE))
{
$updateString .= $columnname[$k] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[$k]]) . "', ";
}
else
{
$updateString .= $columnname[$k] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[$k]]) . "' WHERE " . $columnname[0] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[0]]) . "';";
}
}
if(mysqli_query($connect, $updateString))
{
echo "Daten wurden erfolgreich aktualisiert! </br>";
}
else
{
echo "Es ist ein Fehler aufgetreten... </br>";
}
mysqli_close($connect);
}
My code is working fine at the moment but I'm not managing to get it to work with prepared statements. I hope my question is not too stupid. Can somebody share some thoughts how to realize it with my code or do I have to completly overthink my approach?
Sorry again for my noob question...
Thanks!
Thanks to everybody who answered I managed to get it to work. I used the call_user_func_array function and can now generate the prepared statements for UPDATE and INSERT in one function:
function preparedStatement($tableName, $action)
{
$connect = sqlConnect();
$stmt = $connect->stmt_init();
$columnname = getColumnname($tableName, false, true);
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
$fielddata[] = $columnname[$k];
$fieldvalue[] = $_POST[$columnname[$k]];
}
if ($action == "insert")
{
$fieldvalue[0] = " ";
}
$fieldvalue_join = implode(',', array_map('addquote', $fieldvalue));
$fieldvalue = explode(",",$fieldvalue_join);
$valueCount = count($fieldvalue);
$question_mark = array();
for($i=0; $i<$valueCount; $i++)
{
$question_mark[] = '?';
}
$join_question_mark = implode(",", $question_mark);
$types = '';
foreach($fieldvalue as $param)
{
if(is_int($param))
{
$types .= 'i'; //integer
}
elseif (is_float($param))
{
$types .= 'd'; //double
}
elseif (is_string($param))
{
$types .= 's'; //string
}
else
{
$types .= 'b'; //blob and unknown
}
}
if ($action == "insert")
{
$insertString = "INSERT INTO ".$tableName."(".implode(",",$fielddata).") VALUES (".$join_question_mark.");";
$stmt->prepare($insertString);
$bind_names[] = $types;
}
elseif ($action == "update")
{
$updateString = "UPDATE " . $tableName . " SET ";
for ($k=0; $k<count($columnname, COUNT_RECURSIVE); $k++)
{
if ($k+1 < count($columnname, COUNT_RECURSIVE))
{
$updateString .= $columnname[$k] . " = ?, ";
}
else
{
$updateString .= $columnname[$k] . " = ? WHERE " . $columnname[0] . " = '" . mysqli_real_escape_string($connect, $_POST[$columnname[0]]) . "';";
}
}
$stmt->prepare($updateString);
$bind_names[] = $types;
}
for ($i=0; $i<count($fieldvalue); $i++)
{
$bind_name = 'bind' . $i;
$$bind_name = $fieldvalue[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
if($stmt->execute())
{
$insert_id=$stmt->insert_id;
$stmt->close();
return $insert_id;
}
else
{
echo "Fehler beim Ausführen der Aktion...";
}
}
function addquote($str)
{
if($str[0]=="'" || $str[0]=='"' && $str[strlen($str)-1]=="'" || $str[strlen($str)-1]=="'" )
{
$str=substr($str,1);
$str=substr($str,0,-1);
}
return sprintf("%s", $str);
}
Related
I'm trying to use prepared statements in my SQL but I can't get it working. I'm getting error "SQL translate error: Extra placeholder" when I add something like this to my code
if ($cpucooler_socket != "") {
$myArray = explode(',', trim($cpucooler_socket));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$socket = $myArray[$i];
if ($i === 0) {
$query .= " AND (socket LIKE ?";
$query_params[] = '%' . $socket . '%';
} else if ($i === count($myArray) - 1) {
$query .= " OR socket LIKE ?)";
$query_params[] = '%' . $socket . '%';
} else {
$query .= " OR socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
} else {
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
}
}
What am I doing wrong? What is the right syntax that I should be using in this case? If I don't use the for loop and I add only for example this instead:
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $myArray[0] . '%';
then it's working fine. Here is my full code if it helps:
public function getCompatibleMb($case_format_dosky, $cpu_socket, $ram_typ, $pocet_ram, $intel_socket, $amd_socket, $select_after_id, $search) {
$cpucooler_socket = null;
if(isset($intel_socket) || isset($amd_socket)){
if ($intel_socket != null && $amd_socket != null) {
$cpucooler_socket = $intel_socket.", ".$amd_socket;
} else if($intel_socket != null) {
$cpucooler_socket = $intel_socket;
} else if ($amd_socket != null){
$cpucooler_socket = $amd_socket;
}
} else {
$cpucooler_socket = null;
}
$query_params = array();
$query = "SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1";
if ($cpu_socket != "") {
$query .= " AND socket = ?";
$query_params[] = $cpu_socket;
} else {
if ($cpucooler_socket != "") {
$myArray = explode(',', trim($cpucooler_socket));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$socket = $myArray[$i];
if ($i === 0) {
$query .= " AND (socket LIKE ?";
$query_params[] = '%' . $socket . '%';
} else if ($i === count($myArray) - 1) {
$query .= " OR socket LIKE ?)";
$query_params[] = '%' . $socket . '%';
} else {
$query .= " OR socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
} else {
$query .= " AND socket LIKE ?";
$query_params[] = '%' . $socket . '%';
}
}
}
}
if ($ram_typ != "") {
$query .= " AND ram_type = ?";
$query_params[] = $ram_typ;
}
if ($pocet_ram != "") {
$query .= " AND ram_slots >= ?";
$query_params[] = $pocet_ram;
}
if($case_format_dosky !="") {
$myArray = explode(',', trim($case_format_dosky));
for ($i = 0; $i < count($myArray); $i++) {
if(count($myArray)>1) {
$formfactor = trim($myArray[$i]);
if ($i === 0) {
$query .= " AND (form_factor = ?";
$query_params[] = $formfactor;
} else if ($i === count($myArray) - 1) {
$query .= " OR form_factor = ?";
$query_params[] = $formfactor;
} else {
$query .= " OR form_factor = ?)";
$query_params[] = $formfactor;
}
} else {
$query .= " AND form_factor LIKE ?";
$query_params[] = '%' . $formfactor . '%';
}
}
}
if ($select_after_id != "") {
$decrypted = $this->McryptServices->decryptData($select_after_id);
$query .= " AND id > ?";
$query_params[] = $decrypted;
}
if ($search != "") {
$new_search = str_replace(" ", "%",$search);
$query .= " AND produkt LIKE ?";
$query_params[] = '%'.$new_search.'%';
}
$query .= " LIMIT 32";
$vytah = $this->Database->query($query, $query_params)->fetchAll();
$arr[] = $vytah;
foreach ($arr[0] as $key => $value) {
$arr[0][$key]->{'encryptid'} = $this->McryptServices->encryptData($arr[0][$key]->{'id'});
}
return json_encode($arr);
}
This is the response after an error:
"line":225,"args":[["string","SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1 AND (form_factor = ? OR form_factor = ? OR form_factor = ?) LIMIT 32"],["array",[["string","ATX"],["string","mATX (Micro ATX)"],["string","mITX (Mini ITX)"]]]]}
I've made a simple code to make multiple inserts on the database:
<?php
if (isset($_POST['numb']) && isset($_POST['email1'])) {
$error = false;
$numb = $_POST['numb'];
for ($i = 1; $i <= $numb; $i++) {
if (!isset($_POST['email' . $i])) {
$error = true;
}
}
if ($error == false) {
include 'config.php';
try {
$connection = new PDO($dsn, $user, $pass);
$suc1 = true;
} catch (PDOException $e) {
echo $e->GetMessage();
$suc1 = false;
}
if ($suc1 == true) {
$sql = "INSERT INTO alunos(email, emailKey) VALUES ";
for ($i = 1; $i <= $numb; $i++) {
$BAMBAM[$i] = '(:email' . $i . ', :emailkey' . $i . ')';
$FELIPEFRANCO[$i] = sha1(microtime() . $_POST['email'. $i]);
if ($i != $numb) {
$BAMBAM[$i] = $BAMBAM[$i] . ',';
}
$sql = $sql . $BAMBAM[$i];
}
$insert = $connection->prepare($sql);
for ($i = 1; $i <= $numb; $i++) {
$param1 = 'email' . $i;
$value1 = $_POST['email' . $i];
$param2 = 'emailkey' . $i;
$value2 = $FELIPEFRANCO[$i];
echo '<script>alert("' . $param1 . ' -> ' . $value1 . '")</script>';
$insert->bindParam($param1, $value1, PDO::PARAM_STR);
$insert->bindParam($param2, $value2, PDO::PARAM_STR);
}
try {
$insert->execute();
$suc2 = true;
} catch (PDOException $e) {
echo $e->GetMessage();
$suc2 = false;
}
echo $sql;
} else {
header('Location: addAlunosForm.php?error=internal');
}
} else {
header('Location: addAlunosForm.php?error=fill');
}
} else {
header('Location: addAlunosForm.php?error=fill');
}
?>
There is a test script up there, and, in the alert, it says exactly thiis:
email1 -> 1#gmail.com
email2 -> 2#gmail.com
email3 -> 3#gmail.com
But in the databse, it inserts the 3rd value 3 times:
3
NULL
3#gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL
4
NULL
3#gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL
5
NULL
3#gmail.com
901d4043642394ca30ea83688d944987d266b698
NULL
NULL
Details:
$numb is the number of inserts
This is bizarre. I am working on a new website using WAMP on my pc and I copy and pasted the database functions I created from another site I worked on.
Below is the function. On this new site I'm getting an error (Notice: Undefined offset: 0) whenever there is nothing that matches in the database. But, on the other site (which is hosted externally) I never get that error (never have and I just tested it specifically to make sure).
Obviously, I could just put the "return $rows[0]" in an if statement to prevent this. But, I would like to know what is causing the problem in case I need to make some changes to the old site! I'm kind of worried!
There's also another difference. On the new site I get an error when the $order is NULL, saying that $s3 is undefined. Again, I can fix it easily by just defining it along with $s1 and $s2 at the beginning. But, it works fine on my other site and has for a long time. What on earth is the difference??
function get_row5($table, $field, $where1, $value1, $where2=NULL, $value2=NULL, $where3=NULL, $value3=NULL, $where4=NULL, $value4=NULL, $where5=NULL, $value5=NULL, $order=NULL) {
$rows = array();
global $conn;
connect();
$s1 = "SELECT $field FROM $table WHERE $where1" . '=' . "'$value1'";
$s2 = "";
if ($where2 != NULL) {
if ($value2 == NULL) {
$s2 = " and $where2 is NULL";
} else {
$s2 = " and $where2" . ' = ' . "'$value2'";
}
}
if ($where3 != NULL) {
if ($value3 == NULL) {
$s2 .= " and $where3 is NULL";
} else {
$s2 .= " and $where3" . ' = ' . "'$value3'";
}
}
if ($where4 != NULL) {
if ($value4 == NULL) {
$s2 .= " and $where4 is NULL";
} else {
$s2 .= " and $where4" . ' = ' . "'$value4'";
}
}
if ($where5 != NULL) {
if ($value5 == NULL) {
$s2 .= " and $where5 is NULL";
} else {
$s2 .= " and $where5" . ' = ' . "'$value5'";
}
}
if ($order != NULL) {
$s3 = " ORDER BY $order LIMIT 1";
}
$sql = $s1 . $s2 . $s3;
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
mysqli_free_result($result);
$conn->close();
return $rows[0];
}
You are geting this error because there is no row return from query you can overcome with following code
function get_row5($table, $field, $where1, $value1, $where2=NULL, $value2=NULL, $where3=NULL, $value3=NULL, $where4=NULL, $value4=NULL, $where5=NULL, $value5=NULL, $order=NULL) {
$rows = array();
global $conn;
connect();
$s1 = "SELECT $field FROM $table WHERE $where1" . '=' . "'$value1'";
$s2 = "";
$s3 = "";
if ($where2 != NULL) {
if ($value2 == NULL) {
$s2 = " and $where2 is NULL";
} else {
$s2 = " and $where2" . ' = ' . "'$value2'";
}
}
if ($where3 != NULL) {
if ($value3 == NULL) {
$s2 .= " and $where3 is NULL";
} else {
$s2 .= " and $where3" . ' = ' . "'$value3'";
}
}
if ($where4 != NULL) {
if ($value4 == NULL) {
$s2 .= " and $where4 is NULL";
} else {
$s2 .= " and $where4" . ' = ' . "'$value4'";
}
}
if ($where5 != NULL) {
if ($value5 == NULL) {
$s2 .= " and $where5 is NULL";
} else {
$s2 .= " and $where5" . ' = ' . "'$value5'";
}
}
if ($order != NULL) {
$s3 = " ORDER BY $order LIMIT 1";
}
$sql = $s1 . $s2 . $s3;
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
mysqli_free_result($result);
$conn->close();
if(count($rows))
return $rows[0];
else
return $rows; //<---empty row
}
I have the following code but i am not sure how to check if insert is success. execute returns resource id. I would like to check if success and return all errors on fail.
public function persist()
{
$update = FALSE;
if(!is_array($this->tablePrimaryKey)) {
if(!empty($this->fieldVals[$this->tablePrimaryKey])) {
$update = true;
}
}
if ($update) {
$sql = "UPDATE " . $this->tableName . " SET ";
$binds = [];
foreach ($this->fieldVals as $key=>$val) {
if ($key != $this->tablePrimaryKey) {
if(in_array($key, $this->DATE_IDS)) {
$sql .= '"' . strtoupper($key) . '" = sysdate,';
} else {
$bind = 't_' . $key;
$binds[$bind] = $val;
$sql .= '"' . strtoupper($key) . '" = :' . $bind . ',';
}
}
}
$sql = substr($sql,0,-1);
$sql .= " WHERE " . $this->tablePrimaryKey . " = '" . $this->fieldVals[$this->tablePrimaryKey] ."'";
} else {
$binds = $fields = $date_fields = [];
if(!empty($this->tablePrimaryKey) && !is_array($this->tablePrimaryKey)) {
$this->fieldVals[$this->tablePrimaryKey] = $this->generateNewPrimaryKey();
}
foreach ($this->fieldVals as $key=>$val) {
$bind = ':t_' . $key;
if (in_array($key, $this->DATE_IDS)) {
$date_fields[] = strtoupper($key);
} else {
$binds[$bind] = $val;
$fields[] = strtoupper($key);
}
}
$sql = 'INSERT INTO ' . $this->tableName . '("' . implode('","', $fields);
if(count($date_fields) >0) {
$sql .= '","';
$sql .= implode('","', $date_fields);
}
$sql.='") VALUES (' . implode(',', array_keys($binds));
if(count($date_fields) >0) {
$cnt=0;
foreach($date_fields as $date) {
$cnt++;
if(preg_match('/NULL/i', $this->fieldVals[strtolower($date)], $result)) {
$sql .= ",NULL";
} elseif(isset($this->fieldVals[strtolower($date)])) {
$sql .= ",TO_DATE('" . (new DateTime($this->fieldVals[strtolower($date)]))->format("Y-M-d H:i:s") . "', 'yyyy/mm/dd hh24:mi:ss')";
} else {
$sql .= ",sysdate";
}
}
}
$sql .= ')';
}
$this->oiDb->parse($sql, $binds);
return $this->oiDb->execute();
}
I run $result = $oiRequests->hydrate($reportingRequest)->persist();. $reportingRequest is key,value pair of columns/values. $result contains resource id. $oiRequests is my model.
I have tried
$num_rows = oci_fetch_assoc ($result);
print_r($num_rows);
returns
Warning: oci_fetch_assoc(): ORA-24374: define not done before fetch or execute and fetch in /var/SP/oiadm/docroot/dev/uddins/requestportal/requestportal_ajax.php on line 65
Most of the OCI functions return false on error. This means you can do a simple check on the return value and, if it's false, call oci_error().
For the specific case of checking if an INSERT statement worked you can reference the example code for oci_commit(). The relevant part of that example is duplicated here:
// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
// Use OCI_DEFAULT as the flag for PHP <= 5.3.1. The two flags are equivalent
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
Every time I call a query with my class for select * from table where blank=blank it always comes up "NULL" on a var_dump for the results at the end of the class. I'm still stuck on this and don't know why it's doing it, but it sends no responses for sure, because I'm getting nothing back.
mysqli.class.php
<?php
class DATABASE
{
//set up variables only for this class
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $connection;
private $paramaters = array();
private $results = array();
private $numrows;
//call connection on call of class
public function __construct($db_host, $db_user, $db_pass, $db_name)
{
$this->host = $db_host;
$this->user = $db_user;
$this->pass = $db_pass;
$this->name = $db_name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name) or die('There was a problem connecting to the database! Error #: '. $this->mysqli->connect_errno);
}
//close mysqli connection on class close
public function __destruct()
{
$this->mysqli->close();
}
//query
public function select($fields, $table, $where, $whereVal, $type, $orderByVal, $ASDESC, $limitVal, $sets, $setVal)
{
switch($type)
{
case "regular":
if ($where == null)
{
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = "";
} else {
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
break;
case "orderByLimit":
$queryPre = "SELECT " . $fields . " FROM " . $table;
$querySuff = " ORDER BY " . $orderByVal . " " . $ASDESC . " LIMIT " . $limitVal;
break;
case "update":
if ($where == null)
{
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal;
} else {
$queryPre = "UPDATE " . $table;
//need for loop for multiple sets, check for is_array and do multiple if so.
$querySuff = " SET " . $sets . " = " . $setVal . " WHERE " . $where . " = ?";
}
break;
case "insert":
if ($sets == null)
{
$queryPre = "INSERT INTO " . $table;
$querySuff = " VALUES(" . setVal . ")";
} else {
$queryPre = "INSERT INTO " . $table . " (" . $sets . ")";
$querySuff = " VALUES(" . setVal . ")";
}
case "delete":
if ($where == null)
{
$queryPre = "DELETE FROM " . $table;
$querySuff = "";
} else {
$queryPre = "DELETE FROM " . $table;
$querySuff = " WHERE " . $where . " = ?";
}
}
//$sql = $queryPre . "" . $querySuff;
//var_dump($sql);
//exit;
$stmt = $this->mysqli->prepare($queryPre . "" . $querySuff) or die('There was a problem preparing the Query! Error#: '. $this->mysqli->errno);
if ($whereVal == null)
{
$stmt = $this->bindVars($stmt,$setVal);
} else {
$stmt = $this->bindVars($stmt,$whereVal);
}
$stmt->execute();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ($stmt->fetch())
{
$x = array();
foreach($row as $key => $val)
{
$x[$key] = $val;
}
$results[] = $x;
}
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
}
private function bindVars($stmt,$params)
{
if ($params != null)
{
$types = '';
//initial sting with types
if (is_array($params))
{
foreach($params as $param)
{
//for each element, determine type and add
if(is_int($param))
{
$types .= 'i'; //integer
} elseif (is_float($param))
{
$types .= 'd'; //double
} elseif (is_string($param))
{
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
} else {
if (is_int($params))
{
$types = 'i';
} elseif (is_float($params))
{
$types = 'd';
} elseif (is_string($params))
{
$types = 's';
} else {
$types = 'b';
}
}
$bind_names[] = $types;
if (is_array($params))
{
//go through incoming params and added em to array
for ($i=0; $i<count($params);$i++)
{
//give them an arbitrary name
$bind_name = 'bind' . $i;
//add the parameter to the variable variable
$$bind_name = $params[$i];
//now associate the variable as an element in an array
$bind_names[] = &$$bind_name;
}
} else {
$int0 = 0;
$bind_name = 'bind' . $int0;
$$bind_name = $params;
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($stmt,'bind_param'),$bind_names);
}
return $stmt; //return the bound statement
}
}
?>
example to call and check fields - process_availability.php:
<?php
//require necessary files
require('../config/dbconfig.php');
include('../classes/mysqli.class.php');
//initiate connection
$mysqli = new DATABASE($db_host,$db_user,$db_pass,$db_name);
//take type of check
$checktype = $_POST['type'];
//check the user name
if ($checktype == "username") {
//change post to variable
$username = $_POST['username'];
//check if user name is empty
if ($username == "") {
$validuser = array("empty", "false");
echo implode(',', $validuser);
exit;
}
//if user name is more characters than 30
if (strlen($username) > 30) {
$validuser = array("max", "false");
echo implode(',', $validuser);
exit;
}
//search for same user name in database
$resultsU = $mysqli->select('*','users','username',$username,'regular',null,null,null,null,null);
//var_dump($resultsU);
if (is_array($resultsU))
{
var_dump($resultsU);
foreach($resultsU as $rowU)
{
//return results
if($rowU['username'] == "" || $rowU['username'] == NULL)
{
//user name is blank
$validuser = array("yes", "true");
echo implode(',', $validuser);
exit;
}
else {
//username is not blank, so it's taken
$validuser = array("no", "false");
echo implode(',', $validuser);
exit;
}
}
}
}
And just to show what I'm actually doing with the information, here is a PART of the java (just handles username mostly, there is a ton more for email, ect not included):
fiddle
And, of coarse, the link to the page: page link
I've been fixing other things on here, and on a technicality it works. I get a response if there IS something in the database that matches the username i type, but if there is no match, for some reason it doesn't respond at all.....
Specifically...right at the bottom of the 2nd to last function in the class:
$stmt->close();
//var_dump($results);
if ($results == "" || $results == NULL)
{
return null;
} else {
return $results;
}
When you are returning no results to the client, you need to indicate to the client that this is what you have done, and the code shown above simply outputs nothing in this case. While it is easily possible to handle this empty response correctly on the client side a better solution would be to do one of the following:
If you need the data from the result, json_encode() the results before sending them back to the client. This would mean that if the were no results you would return an empty array, but it would still be valid JSON and crucially you can easily check whether the result array is empty on the client side using result.length.
If you don't actually need the result data and all you need is to determine whether there were any results, you can simply return a 1 or a 0. This kind of boolean response takes minimal bandwidth and minimal processing, and the best thing about it is all you need to do is evaluate it as a boolean on the client side - i.e. if (result) { /* do stuff */ }