I have a selet function where I pass two variables. The table and where.
However, whatever I put for where it always displays id = 1.
Could this be because it is recognising that id has a value and setting it to 1 or am I completely off the mark here?
The function is below:
public function select($table, $where){
$sql = "SELECT * FROM $table WHERE $where";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1){
return $this->processRowSet($result, true);
}
return $this->processRowSet($result);
}
The call to the function is:
$rowSet = $db->select('users','username = wayne');
Or is it the way I am setting username in the parameter?
username is a String then it is necessary to write
$rowSet = $db->select('users','username = "wayne"');
Related
I am learning the Zend Framework. Now I need to attach a prepared statement to prevent SQL injection in the Zend Framework.
So I am sharing some functions here which I am using so if you can tell me how I can attach a prepared statement in these Zend Database Query Functions it will be helpful.
public function getRowByID($id) {
$row = $this->fetchRow("id = '$id'");
if (!$row) {
return false;
}
return $row;
}
public function getbyProjectID($projectid) {
$query = "SELECT * FROM auth where projectid = '$projectid'";
$result = $this->getAdapter()->query($query);
return $result->fetchAll();
}
public function updateRowByUserProject($username, $projectid) {
$query = "UPDATE auth SET iscurrent=0 WHERE username = '$username'";
$result = $this->getAdapter()->query($query);
$query1 = "UPDATE auth SET iscurrent=1 WHERE username = '$username' AND projectid = '$projectid'";
$result1 = $this->getAdapter()->query($query1);
$affectedRow = $result1->rowCount();
if($affectedRow == 1){
return true;
}else{
return false;
}
}
For fetching you could use Zend_Db_Select Class methods for preparing a query and executing it, passing variables in questionmark places (placeholders which will be escaped from special characters) after comma (possible multiple questionmarks, passing variables from left to right):
public function getRowByID($id) {
$table = $this->getTable();
$select = $table->select();
$select->where('id = ?', $id);
$row = $table->fetchRow($select);
if (!$row) {
return false;
}
return $row;
}
For your second method getByProjectId() it depends if you are in proper model (like Auth_Model_Auth) or you want to access data from another table
public function getbyProjectID($projectid) {
$table = $this->getTable();
$select = $table->select();
$select->where('projectid = ?', $projectid);
$result = $table->fetchAll($select);
return $result;
}
And for updating you can pass an array to 'update' method in same style like for fetching data. Key of an array must be a column name of your table.
public function updateRowByUserProject($username, $projectid) {
$table = $this->getTable();
// Data you want to insert/update
$data = [
'iscurrent' => 0
];
// Where you want to update it
$where = [
'username = ?' => $username
]
$result = $table->update($data, $where);
$data1 = [
'iscurrent' => 1
]
$where1 = [
'username = ?' => $username,
'projectid = ?' => $projectid
]
$result1 = $table->update($data1, $where1);
}
EDIT:
For both questions from comments you could achieve this by using quoteInto method, which also escapes data from special chars.
In first case you prepare a $where variable, which contains what record you want to delete:
$table = $this->getTable();
$where = $table->getAdapter()->quoteInto('projectid = ?', $projectid);
$isDeleted = $table->delete($where);
In second case you can do exactly the same:
$query = "SELECT COUNT(*) AS total FROM applications WHERE projectid IN (SELECT projectid FROM auth WHERE projectid = ?)";
$query = $this->getAdapter()->quoteInto(?, $projectid):
...
But you should try to avoid writing big queries in one variable and then executing them. I would suggest you to get to know with this:
https://framework.zend.com/manual/1.11/en/zend.db.select.html
Really well explained how to use Zend methods for this purpose.
I have created the following function to fetch data from my database, but its capabilities are limited. Currently it can fetch one value at a time, which is fine for fetching the value of one column of one row, but as I progress with my work, I now want to be able to fetch multiple values in one call.
The Function:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data[$value];
}
mysqli_close($connection);
}
How I currently use it to fetch multiple values:
// Define variables
$x1 = retrieve("x1");
$x2 = retrieve("x2");
$x3 = retrieve("x3");
$x4 = retrieve("x4");
$x5 = retrieve("x5");
$x6 = retrieve("x6");
$x7 = retrieve("x7");
$x7 = retrieve("x8");
I have read other questions here on Stack Overflow, but none of them solves my problem as I use an optional parameter, which makes my life hard. For example, I thought of implementing the splat operator to allow unlimited parameters, but as I use the optional parameter $identifier, I can't make it into something like:
function retrieve($identifier = null, ...$value) {}
because it will use the first parameter as the identifier when I omit it.
I'm sure that regarding performance it would be better if I could fetch all the necessary values in one call of the function retrieve() instead of using it as shown above and that's why I would like to know:
How can I edit this function in order to fetch more values at once?
Calling it like so:
$x = retrieve($y);
$x1 = $y["x1"];
$x2 = $y["x2"];
...
EDIT:
Thanks to Manish Jesani for his help! I used his answer and modified to do exactly what I want. For anyone that may be interested in the future, here's the code:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$values = array();
$identifier = (is_null($identifier)) ? "`ID` = '1'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if (is_array($value)) {
foreach($value as $_value) {
$values[$_value] = $data[$_value];
}
return $values;
}
else {
return $data[$value];
}
}
mysqli_close($connection);
}
You can call the function with as many parameters you want. Τo do this you have to use func_num_args() to get all of them, as shown below:
function retrieve() {
$args = func_num_args();
$query = "SELECT '".implode("','", func_get_args())."' FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
}
mysqli_close($connection);
}
You can call this function like this: $params = retrieve('x1','x2','x3').
Alternatively, you can retrieve them as variables list($x1, $x2, $x3) = retrieve('x1','x2','x3').
Please try this:
function retrieve($value, $identifier = null) {
// Check if identifier is given
$return = array();
$identifier = (is_null($identifier)) ? "`ID` = '{$_SESSION["ID"]}'" : $identifier;
// Connect to the database
$connection = connect("limited");
// Pass query, get result and fetch value out of it
$query = "SELECT * FROM `users` WHERE $identifier";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
if(is_array($value))
{
foreach($value as $_value)
{
$return[$_value] = $data[$_value];
}
}
else
{
$return[$value] = $data[$value];
}
return $return;
}
mysqli_close($connection);
}
$x = retrieve(array("x1","x2","x3","x4","x5","x6"));
I have this function which returns only one row, How can I modify the function so that it returns more than one row?
public function getVisitors($UserID)
{
$returnValue = array();
$sql = "select * from udtVisitors WHERE UserID = '".$UserID. "'";
$result = $this->conn->query($sql);
if ($result != null && (mysqli_num_rows($result) >= 1)) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (!empty($row)) {
$returnValue = $row;
}
}
return $returnValue;
}
There is a function in mysqli to do so, called fetch_all(), so, to answer your question literally, it would be
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ".intval($UserID);
return $this->conn->query($sql)->fetch_all();
}
However, this would not be right because you aren't using prepared statements. So the proper function would be like
public function getVisitors($UserID)
{
$sql = "select * from udtVisitors WHERE UserID = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $UserID);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_all();
}
I would suggest storing them in an associative array:
$returnValue = array();
while($row = mysqli_fetch_array($result)){
$returnValue[] = array('column1' => $row['column1'], 'column2' => $row['column2']); /* JUST REPLACE NECESSARY COLUMN NAME AND PREFERRED NAME FOR ITS ASSOCIATION WITH THE VALUE */
} /* END OF LOOP */
return $returnValue;
When you call the returned value, you can do something like:
echo $returnValue[0]['column1']; /* CALL THE column1 ON THE FIRST SET OF ARRAY */
echo $returnValue[3]['column2']; /* CALL THE column2 ON THE FOURTH SET OF ARRAY */
You can still call all the values using a loop.
$counter = count($returnValue);
for($x = 0; $x < $counter; $x++){
echo '<br>'.$rowy[$x]['column1'].' - '.$rowy[$x]['column2'];
}
I've created a function that suppose to return all row in database to browser, but it is return only one value. Below is my table:
And this is my code:
SqlDatabase.php Classes:
public function query($sql){
$result = mysqli_query($this->connection, $sql);
return $result;
}
test.php:
$database = new SqlDatabase;
//testing function
public static function find_comments($photo_id=0){
global $database;
$sql = "select * from comments";
$sql .= " where photograph_id = {$photo_id}";
$sql .= " order by created ASC";
print_r(self::sql_find($sql));
}
// This is a testing function
public static function sql_find($sql){
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_assoc($result_set)){
$object_array = $row['author'];
} return $object_array;
}
When i try to run this function, It is only return one last value "vai het loc" to PHP:
Comments::find_comments(77);
I tried several ways and do researchs but haven't found any solutions yet. Not sure what am i missing. Need some guide to fetch all row in photograph_id not only one value.
Thanks for helps.
You're overwriting the value, not appending it to the array.
Change this line:
$object_array = $row['author'];
to this:
$object_array[] = $row['author'];
In your sql_find() function and you should get the object.
I am writing a script to access a specific detail about the user and I was hoping to make the database query be function.
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ID'";
$s = mysql_query($q);
$r = mysql_fetch_array($s);
}
But when I try and use it it will not access the row the way I want it to.
$user = '999';
connectUser($user)
echo $r['name'];
But if I put echo $r['name']; in the function it will work.
your function is not returning anything. add return $r['name'] at the end of function.
then echo connectUser($user);
thare are 2 major problems in your code
the function doesn't return anything and you don't assign it's result to a variable.
Your variables doesn't match. $ip doesn't seem the same variable with $ID
so, this one would work
function connectUser($id) {
$q = "SELECT * FROM users where ID=".intval($id);
$s = mysql_query($q);
return mysql_fetch_array($s);
}
$user = '999';
$r = connectUser($user)
echo $r['name'];
That's because the variable $r isn't being returned by the function, so it's never being set outside of the function. Here's what you should have:
function connectUser($ip) {
$q = "SELECT * FROM users where ID='$ip'";
$s = mysql_query($q);
return mysql_fetch_array($s);
}
And then outside have:
$user = '999';
$r = connectUser($user)
echo $r['name'];
You might also want to take a look at this question: prepared statements - are they necessary
This function is not working,
as you did not supplied the database connection into function,
and you did not return anything (PHP will return NULL)
Please understand what is variable scope first,
and the function
A workable example, can be like :-
function connectUser($db, $ip)
{
$q = "SELECT * FROM users where ID='$ID'"; // vulnerable for sql injection
$s = mysql_query($q, $db); // should have error checking
return mysql_fetch_array($s); // value to be returned
}
How to use :-
$db = mysql_connect(...);
$res = connectUser($db, "some value");