queryPrep.php 2.19 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
/*
splat operator (...) :
	http://coursesweb.net/php-mysql/splat-operator-php_t
	https://stackoverflow.com/questions/744145/passing-an-array-as-arguments-not-an-array-in-php
		splat for older versions
*/

/*
	runs a prepared query and returns a result

	call RESULT->FREE() on the result
*/
include_once(dirname(__FILE__)."/SQLlogin.php");
include_once(dirname(__FILE__)."../exceptions.php");


function resultQuery($queryString, $paramArr, $paramTypes = NULL){
	$con = SQLlogin();
	//echo "hello 1";
	$errorCode = 0;
	if($stmt = $con->prepare($queryString)){// no terminating ;
		if(sizeof($paramArr)>0){
			$paramTypes = getParamTypes($paramArr);
			$stmt->bind_param($paramTypes, ...$paramArr);
		}
		$stmt->execute();
		$result = $stmt->get_result();
		$stmt->close();
	}else{
		$errorCode = 400;//statement prep error
	}
	SQLclose($con);
	if($errorCode !== 0) throw new PrepException("resultQuery exception", 401);
	return $result;
}

/*
	runs a statement, but doesn't return a result
*/
function noResultSQL($SQLstring, $paramArr, $paramTypes = NULL){
    $con = SQLlogin();
    //echo "hello no 1";
    $worked = TRUE;
    if($stmt = $con->prepare($SQLstring)){
    	if(sizeof($paramArr)>0){
			$paramTypes = getParamTypes($paramArr, $paramTypes);		
			$stmt->bind_param($paramTypes, ...$paramArr);
		}
        $stmt->execute();
        $stmt->close();
    }else{
        $worked = 400;//statement prep error 
    }
    SQLclose($con);
	if($worked !== TRUE) throw new PrepException("noResultSQL exception", 400);
}

/*
THIS DOESN'T HANDLE BLOB URLS

This takes an array of parameters and returns a string 
that has a character for each parameter from one of the following:
	i 	for integer
	d 	for double
	s 	for string
	b 	for blob

this is used a the first param in bind_param
*/
function getParamTypes($paramArr, $paramTypes = NULL){
	if ($paramTypes !== NULL) return $paramTypes;
	$retStr = "";
	foreach($paramArr as $v){
		if(is_int($v)){
			$retStr .= "i";
		}elseif(is_double($v)){
			$retStr .= "d";
		}elseif(is_string($v)){
			$retStr .= "s";
		}else{
			echo $v."<br>@ queryPrep.getParamTypes()";
			print_r($paramArr);
			throw new assertionError();
		}
		//add blob here when you need it
	}
	return $retStr;
}

?>