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
Related
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);
}
I'm new to my sqli the improved version of PHP.
<?php
// Class for the transparent access of MySQL
$con = mysqli_connect("host","database","port","user","passwd","conn","querytext","query_id","err","errno","record = array();","row = 0;","rows = 0;") or die ("Some error occured during connection " . mysqli_error($con));
function query($querystring) {
$this->querytext = $querystring;
$this->query_id = mysqli_query($this->querytext, $this->con);
$this->Errno = mysqli_errno($this->conn);
$this->Error = mysqli_error($this->conn);
if($this->query_id) {
if(strtolower(substr(trim($this->querytext),0,6)) == 'select'){
$this->rows = mysqli_num_rows($this->query_id);
} else {
$this->rows = 0;
}
$this->row = 0;
} else {
$this->rows = 0;
$this->row = 0;
$this->halt("Query failed!");
}
}
function setpassword($newpasswd){
$querystring = sprintf("SET PASSWORD = PASSWORD('%s')", $newpasswd1);
return $this->query($querystring);
}
function next_record() {
if($this->row < $this->rows) {
$this->record = mysql_fetch_array($this->query_id);
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row +=1;
$status = is_array($this->record);
} else {
$status = FALSE;
}
return $status;
}
function seek($pos) {
if(($pos >= 0 && $pos < $this->rows) &&
mysql_data_seek($this->query_id, $pos)) {
$this->Errno = mysql_errno($this->conn);
$this->Error = mysql_error($this->conn);
$this->row = $pos;
}
}
function close() {
$this->query = "";
$this->rows = 0;
$this->row = 0;
mysql_close($this->conn);
}
function htmltable () {
$resulttable='';
if($this->rows > 0){
$resulttable=sprintf("<table %s>", $tableoptions);
while($this->next_record()) {
/* Ueberschriften */
if($this->row == 1) {
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<th>" . $key . "</th>";
}
$resulttable=$resulttable . "</tr>\n";
reset($this->record);
} /* Ende Ueberschriften */
$resulttable=$resulttable . "<tr>";
while(list($key, $value)=each($this->record)){
$resulttable=$resulttable . "<td>" . $value . "</td>";
}
$resulttable=$resulttable . "</tr>\n";
}
$resulttable=$resulttable . "</table>\n";
}
return $resulttable;
}
?>
You should be connecting to the database using PDO as it is more secure: http://php.net/manual/en/book.pdo.php
These tutorials are pretty good to follow: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://crewow.com/PHP-MySQL-Simple-Select-using-PDO-in-Bootstrap.php
Also, please make sure that your database credentials are in a separate file that gets included into the file you use to connect to the database.
I am using a php script that handles the backup & restore of my databases. There are several problems with it but I shall post 1 error at a time. When I click restore backup button I am getting the error in the title.
I am not experienced enough to troubleshoot this error and would appreciate some help from the experts. I have posted my code where the error occurs, but if you need to see anything else please let know. The error occurs at line 109. Thanks
PHP V5.3.13
MYSQL V5.5.24
APACHE V2.2.22
<?php
function restoredata($uploadedfile, &$ustartindex, &$uti, &$ulen, &$ucount, &$name, &$limit, $restoremethod)
{
global $host, $username, $passwd, $charset, $port, $upload_path, $backup_path;
$sql = '';
$zip = new ZipArchive();
$filename = $upload_path . '/' . $uploadedfile;
if (!is_file($filename)) {
$filename = $backup_path . '/' . $uploadedfile;
}
if ($zip->open($filename) !== TRUE) {
return "Cannot open file\n.";
}
try {
$dbName = $zip->getFromName('database.txt');
if ($restoremethod == '0') {
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
}
else {
if ($uti == 0 && $ustartindex == 0) {
$conn = mysqli_connect($host, $username, $passwd, 'mysql', $port);
}
else {
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
}
}
if (!$conn) {
return 'Could not connect ' . mysqli_error($conn);
}
if (!mysqli_set_charset($conn, $charset)) {
mysqli_query($conn, 'SET NAMES ' . $charset);
}
$tables = $zip->getFromName('tables.txt');
if ($tables === false) {
$zip->close();
return "Could'nt find tables";
}
$limit = intval($zip->getFromName('limit_info.txt'));
$tables = explode(',', $tables);
$ulen = count($tables);
if ($uti < $ulen) {
if ($uti == 0 && $ustartindex == 0) {
if ($restoremethod == '1') {
$sql = $zip->getFromName($dbName . '.sql');
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($i = 0; $i < count($sql) - 1; $i++) {
$result = mysqli_query($conn, $sql[$i] . ';');
if (!$result) {
mysqli_close($conn);
$zip->close();
return 'Could not run query 1: ' . mysqli_error($conn);
}
}
}
mysqli_close($conn);
$conn = mysqli_connect($host, $username, $passwd, $dbName, $port);
if (!$conn) {
$zip->close();
return 'Could not connect ';
}
for ($i = 0; $i < $ulen; $i++) {
$name = $tables[$i];
$table = '`' . $name . '`';
$sql = $zip->getFromName($table . '.sql');
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($j = 0; $j < count($sql) - 1; $j++) {
$result = mysqli_query($conn, $sql[$j] . ';');
if (!$result) {
mysqli_close($conn);
$zip->close();
return 'Could not run query 2: ' . mysqli_error($conn);
}
}
}
}
}
}
mysqli_autocommit($conn, FALSE);
// mysqli_begin_transaction ($conn, MYSQLI_TRANS_START_READ_ONLY );//READ ONLY transaction
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_WRITE); <---ERROR HERE
$name = $tables[$uti];
$table = '`' . $name . '`';
$ucount = intval($zip->getFromName($table . '.txt'));
$sql = $tables = $zip->getFromName($table . '/offset' . $ustartindex . '.sql');
$nerrors = 0;
$serrors = '';
if ($sql !== false) {
$sql = explode(';' . chr(10) , $sql);
for ($i = 0; $i < count($sql) - 1; $i++) {
$sql[$i] = str_replace('NULL', "''", $sql[$i]); //avoid NULL errors
$result = mysqli_query($conn, $sql[$i] . ';');
if (!$result) {
$serrors.= 'Could not run query in ' . $table . ' : ' . mysqli_error($conn) . '<br />';
$nerrors+= 1;
break;
}
}
$ustartindex+= $limit;
}
else {
$uti+= 1;
$ustartindex = 0;
}
if (!mysqli_commit($conn)) {
return "Transaction commit failed";
}
if ($nerrors > 0) {
mysqli_close($conn);
$zip->close();
return $serrors;
}
}
mysqli_close($conn);
$zip->close();
}
catch(Exception $e) {
return var_dump($e->getMessage());
}
return true;
}
?>
I will add that this is not my script but it does all all I need it to do including showing the progress of the backup, which visually is better than just a white page.
I would if possible like to sort these errors out and have a working script. Many thanks.
From http://php.net/manual/en/mysqli.begin-transaction.php, mysqli_begin_transaction is only supported from php 5.5.0 onwards. As your running 5.3 it won't work.
You could remove the transaction and it would work, especially as your originally trying to set a read-only transaction. Also remove the commit.
I would remove the following line as this would rely on transactions working as you'd expect.
mysqli_autocommit($conn, FALSE);
If you NEED to stay on 5.3 then...
mysqli_query($conn, "START TRANSACTION");
I wonder if someone could advise me here. I have a page where I am updating information in a database, from the previous page I post any new images (with a caption too) and I have a checkbox for deleting images. On the processing page I have the following code:
<?php
session_start();
$dbhost = 'removed';
$dbuser = 'removed';
$dbpass = 'removed';
$dbname = 'removed';
function reArrayFiles($file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
}catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$soldier_pre_images = explode(",", $row['soldier_images']);
}
if($_POST['deletephoto']){
$imagestodelete=$row['soldier_images'];
$captionstodelete=$row['soldier_images_captions'];
foreach($_POST['deletephoto'] as $todelete){
$deleteexplode = explode("--",$todelete);
echo $deleteexplode;
$deleteexplodepath = $deleteexplode[0];
$deletecaption=$deleteexplode[1];
$imagesafterdelete= str_replace($deleteexplodepath.",","",$imagestodelete);
echo $imagesafterdelete;
$captionsafterdelete = str_replace($deletecaption."--","",$captionstodelete);
echo $captionsafterdelete;
$unlinkpath = str_replace('site url','..',$deleteexplodepath);
unlink($unlinkpath);
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $imagesafterdelete, ":captions" => $captionsafterdelete, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
if ($_FILES['photo']) {
$file_ary = reArrayFiles($_FILES['photo']);
$capcount = 0;
foreach ($file_ary as $file) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $file["name"]);
$extension = end($temp);
if ((($file["type"] == "image/gif")||($file["type"] == "image/jpeg")||($file["type"] == "image/jpg")||($file["type"] == "image/pjpeg")||($file["type"] == "image/x-png")||($file["type"] == "image/png"))&&($file["size"] < 9000000) && in_array(strtolower($extension), $allowedExts)) {
if ($file["error"] > 0) {
$file_error = "Return Code: " . $file["error"] . "<br>";
} else {
$newfilename = "../assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$file_fullname = "site urlv/assets/uploads/images/" . $_POST['soldier_id'] . "/" . $file["name"];
$new_caption = $_POST['image_captions'][$capcount];
if (file_exists($newfilename)) {
$file_exists = $file["name"] . " already exists. ";
} else {
if(is_dir("../assets/uploads/images/" . $_POST['soldier_id'])){
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}else{
mkdir("../assets/uploads/images/" . $_POST['soldier_id'], 0777, true);
move_uploaded_file($file["tmp_name"],$newfilename);
if (strlen($uploaded_images)>1){
$uploaded_images = $uploaded_images . ",". $file_fullname;
}else{
$uploaded_images = $file_fullname;
}
if (strlen($uploaded_captions)>1){
$uploaded_captions = $uploaded_captions . "--". $new_caption;
}else{
$uploaded_captions = $new_caption;
}
}
}
if (strlen($row['soldier_images'])>1){
$uploaded_images = $row['soldier_images'] . ",". $uploaded_images;
}else{
$uploaded_images = $uploaded_images;
}
}
} else {
$file_invalid = "The file is not a jpg/gif/png file, or is larger than 20mb. Please try again.";
}
$capcount = $capcount+1;
}
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$dbname, $dbuser, $dbpass);
$dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbo->prepare("UPDATE `soldier_info` SET `soldier_images`= :image, `soldier_images_captions`= :captions WHERE `soldier_id`= :id");
$q->execute(array(":image" => $uploaded_images, ":captions" => $uploaded_captions, ":id" => $_POST['soldier_id']));
}catch (PDOException $e) {
$db_error = "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
$query="SELECT * FROM `soldier_info` WHERE `soldier_id` = " . $_POST['soldier_id'] ;
foreach ($dbo->query($query) as $row) {
$firstname = $row['firstname'];
$surname = $row['surname'];
$yearofbirth = $row['yearofbirth'];
$dateofdeath = date("d/m/Y", strtotime($row['dateofdeath']));
$ageatdeath = $row['ageatdeath'];
$regiment = $row['regiment'];
$battallion_brigade = $row['battallion_brigade'];
$Coybty = $row['Coy/bty'];
$rank = $row['rank'];
$solider_number = $row['soldier_number'];
$Next_of_Kin = $row['Next_of_Kin'];
$CWGC = $row['CWGC'];
$Place_Died = $row['Place_Died'];
$Connection_to_Wymeswold = $row['Connection_to_Wymeswold'];
$Cemetery = $row['Cemetery'];
$LRoH = $row['LRoH'];
$Grave = $row['Grave'];
$Memorial = $row['Memorial'];
$Pier_Face = $row['Pier_Face'];
$Other_Mem = $row['Other_Mem'];
$Other_Details = $row['Other_Details'];
$soldier_images = explode(",", $row['soldier_images']);
$soldier_images_captions = explode("--", $row['soldier_images_captions']);
}
$dbo = null;
?>
This isn't a live site right now and is in testing/dev. However the issue I am seeing is that, all the queries are running, but the page loads up as though the select has run first (by this I mean that the records returned are those from before the updates as processed. Can I force this select to run last so that it gets the latest records?
I think you get the 'original' data on the last select because you are running the queries on different connections. Hence they will live in isolated transactions, that might not be properly committed when the last select runs.
If you run them all in the same PDO object I think it will work.
(If you take POST parameters and concatenate them into SQL your server will be hacked. It's just a matter of time and you have the URL here for everyone to see.)
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 */ }