Function returns 1 instead of result (PDO) - function

I have a function which is printed below. THis is meant to dynamicly draw user data from the database using PDO (that situation is clear and all works well). But, instead of returning the result (i e. an email for you("email)), it returns the number 1.
Here's my setup:
public function you($row) {
if(isset($_COOKIE["SK"])) {
$pw = $this->baseXencode($_SESSION["password"]);
$usr = $this->baseXencode($_SESSION["username"]);
$q = "SELECT $row FROM SN_users WHERE username=':USR' AND password=':PW'";
$this->netCore->q($q);
$this->netCore->bind(":PW", $pw);
$this->netCore->bind(":USR", $usr);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
} else {
$q = "SELECT $row FROM SN_users WHERE username='Anonymous' AND password='Anonymous'";
$this->netCore->q($q);
$result = $this->netCore->single();
$result = $result[$row];
return $result;
}
}
}
$this->netCore->q() = PDO query
$this->netCore->single() PDO fetch(PDO::FETCH_ASSOC)
As for ->bind, self-explanatory.
Please help, will be very much appreciated.^^

When using parametrized queries, you don't put the parameters in quotes. That prevents the parameters from being substituted, since it's treated as a literal string. So it should be:
$q = "SELECT $row FROM SN_users WHERE username=:USR AND password=:PW";
I'm surprised it's returning 1. I'd expect your code to cause an error, because single() should be returning false, and false[$row] is not valid.
You should also check that a row was returned; if the username and password are not valid, you won't get an result. So it should be:
$result = $this->netCore->single();
if ($result) {
return $result[$row];
} else {
return false;
}
And the caller of you() needs to check the value as well.

Related

codeigniter 3 $query = $this->db->query($queri_str); return 0 result

Good morning,
I have a problem with mysql and coeigniter 3.
if I request data with
$ query = $ this-> db-> query ($ queri_str);
it does not give me results.
if I enter the query on phpmyadmin it shows me two results.
$ queri_str = 'SELECT * FROM `my_table` WHERE` id_mytable2` = "'. $ id_name. '"';
The database tables were created with mysql workbench and automatically the reference to the main table with a 1: n ratio was added
Try this query
$this->db->select('*');
$this->db->where('id', '58e5j0m5bqrs7hk8suokko28hj7ni0v6');
$result = $this->db->get('ci_sessions')->result_array();
print_r($result);
Try this solution, you want to do a normal select,I don't know the query your wrote but
public fucntion get_data($id){
$this->db->select('*');
$this->db->from('your_table');
$this->db->where('id','=' ,'$id');
$query = $this->db->get();
$data = $query->result_array();
return $data;
}
the problem is back.
I'll explain.
function myfunction($id_myname) {
$this->db->select('*');
$this->db->where('id_myname', $id_myname);
//$query = $this->db->get('my_table');
$query = $this->db->get('my_table');
//print_r($query);
//var_dump($query);
if ( !$query ){
$error = $this->db->error(); // Has keys 'code' and 'message'
}
return $query->result();
}
when I call this function an empty value comes back to me.
While if I enter the value of the query in phpmyadmin I find two values

What's the best way to fetch an array

Alright, so I believe that there is a better way that I can fetch an array from the database, here's the code right now that I have.
$id = 1;
$userquery = mysql_query("SELECT * FROM login WHERE id='$id'");
while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) {
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
So If I am not wrong, you want a better way to get all the returned rows from mysql in a single statement, instead of using the while loop.
If thats the case, then I must say mysql_ drivers do not provide any such functionality, which means that you have to manually loop through them using foreach or while.
BUT, since mysql_ is already depricated, you are in luck! you can actually switch to a much better and newer mysqli_ or the PDO drivers, both of which DO actually have functions to get all the returned rows.
For mysqli_: mysqli_result::fetch_all
For PDO : PDOStatement::fetchAll
Eg.
mysqli_fetch_all($result,MYSQLI_ASSOC);
// The second argument defines what type of array should be produced
// by the function. `MYSQLI_ASSOC`,`MYSQLI_NUM`,`MYSQLI_BOTH`.
Like the comments already told you: PHP's mysql driver is deprecated. And you should use prepared statements and parameters.
for example in PDO your code would look something like this:
//connection string:
$pdo= new PDO('mysql:host=localhost;dbname=my_db', 'my_user', 'my_password');
//don't emulate prepares, we want "real" ones:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//use exception-mode if you want to use exception-handling:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = 1;
//it's always better to strictly use backticks for db-names (db, tables, fields):
$sql = "SELECT * FROM `login` WHERE `id` = :id";
try
{
//create your prepared statement:
$stmt = $pdo->prepare($sql);
//bind a parameter and explicitly use a parameter of the type integer (in this case):
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
//execute the query
$stmt->execute();
}
catch(PDOException $e)
{
exit("PDO Exception caught: " . $e->getMessage());
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
here you go: your PHP-MySQL routine is save against SQL-injections now and no longer uses deprecated PHP-functions! it's kinda state of the art ;)

Statements works in SQL, but not in PDO

I'm converting from SQL to PDO, and everything has gone well until this statement.
My SQL does what it should and does NOT output the message "This user has no private images". But for some reason, when changing to PDO, the same message is shown when it should not be.
Any ideas?
Original SQL:
$result = mysql_query("SELECT * FROM tbl_private_photos WHERE profile = $usernum AND photo_deleted != 'Yes' LIMIT 1");
if (mysql_num_rows($result)!==1) { die("This user has no private images");}
My PDO:
$sql = "SELECT * FROM tbl_private_photos WHERE profile = :usernum AND photo_deleted != 'Yes' LIMIT 1";
$q = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':usernum',$usernum,PDO::PARAM_INT);
$q->execute();
if($r = $q->fetch(PDO::FETCH_ASSOC)!==1)
{
die("This user has no private images");
}
PDO::fetch() returns in this case an array or false. You don't want to compare the fetch result explicitly to the integer 1 then assign it to a variable--it will always be true because a 1 !== array() is always true, and 1 !== false is always true.
Instead you should see if your result set is empty or false.
Try this instead:
$r = $q->fetch(PDO::FETCH_ASSOC);
if(empty($r))
{
die("This user has no private images");
}

PHP PDO succinct mySQL SELECT object

Using PDO I have built a succinct object for retrieving rows from a database as a PHP object with the first column value being the name and the second column value being the desired value.
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
I now want to apply it to a function with 2 parameters, the first containing the table and the second containing any where clauses to then produce the same result.
function select($table,$condition){
$sql = "SELECT * FROM `$table`";
if($condition){
$sql .= " WHERE $condition";
}
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
}
The idea that this could be called something like this:
<?php select("options","class = 'apples'");?>
and then be used on page in the same format as the first method.
<?php echo $option['green'];?>
Giving me the value of the column named value that is in the same row as the value called 'green' in the column named field.
The problem of course is that the function will not return the foreach data like that. That is that this bit:
foreach($sodb->query($sql) as $field){
return $table[$field['name']] = $field['value'];
}
cannot return data like that.
Is there a way to make it?
Well, this:
$sql = "SELECT * FROM `site`"; $site = array();
foreach($sodb->query($sql) as $sitefield){
$site[$sitefield['name']] = $sitefield['value'];
}
Can easily become this:
$sql = "SELECT * FROM `site`";
$site = array();
foreach( $sodb->query($sql) as $row )
{
$site[] = $row;
}
print_r($site);
// or, where 0 is the index you want, etc.
echo $site[0]['name'];
So, you should be able to get a map of all of your columns into the multidimensional array $site.
Also, don't forget to sanitize your inputs before you dump them right into that query. One of the benefits of PDO is using placeholders to protect yourself from malicious users.

Codeigniter - Perform action if database query returns no results

How can I return a value of 'no data found' if my query returns no results???
This is my code:
function getTerms($letter) {
$this->db->select('term, definition');
$this->db->from('glossary');
$this->db->where(array('letter' => $letter));
$query = $this->db->get();
foreach ($query->result() as $row) {
$data[] = array(
'term' => $row->term,
'definition' => $row->definition
);
}
return $data;
}
It currently returns the $data variable even if the query returns no results which is giving me php errors. How can I check that there are results before returning the $data array.
Simply check that the query returns at least one row:
if ($query->num_rows() > 0) {
// query returned results
} else {
// query returned no results
}
Read more in the docs
It currently returns the $data variable even if the query returns no results which is giving me php errors.
It's a good habit to initialize the array that you intend to build:
$data = array();
// Loop through possible results, adding to $data
If there are no results you'll get an empty array returned, then check that in your controller.
This way, at least the variable is defined and you won't get notices.
What about to give initial empty array value for $data
Just put
$data = array();
before foreach
<?php
return is_array($data) ? $data : array();
}