Issue with returning value in php function - php

I'm new in programming and especially with php and MySQL. I have to create dynamic web site for homework. My problem is with the function below. I want it to return int value of tag by given tag name (string). But in my case the function returns every time '1'. Can anyone help me to solve this problem, thanks.
public function getTagIdByName(string $tagName) : int
{
$statement = self::$db->prepare("SELECT tags.id FROM tags WHERE tags.name = ? ");
$statement->bind_param("s", $tagName);
$result = $statement->execute();
return $result;
}

The problem is that you're returning the result of execute(), but that function doesn't actually give you your query result. You need to fetch results after making sure the execution was successful.
//don't forget to error-check before using query results
$statement->execute() or die($statement->error);
$result = $statement->get_result(); //retrieve results for processing
if(!$result->num_rows) return null;//if the id was not found in the DB
else return $result->fetch_assoc()['id'];

You can achieve easily with
$data = $result->fetch_assoc();
return $data['id']; // you can change with which you want to return with field name
And whichever you can use your returned values.

Related

What kind of object can I send to this view in order to get this PHP code to work?

I am terrible at PHP and I need to retrieve data from a database and give it to an index.php view. The view is pre-made and has this code:
//This is simplified - it has error handling that is not shown
$results = getAll($tableName);
//This is the line where it is failing
//Undefined Offset
$columns = empty($results) ? array() : array_keys($results[0]);
$idColumn = $columns[0];
There is all the rest of it but I just need to know what on earth it is that this bit of code is expecting. I have not even got the first clue what is supposed to be sent to this thing. I just need to get it to work.
This is what I have tried so far:
function getAll($tablename)
{
$mysqlConnection = getDbConnection();//Just the normal PDO db connection
$sql = "SELECT * FROM ".$tablename;
$sth = $mysqlConnection->prepare($sql);
$sth->execute();
$resultSet = $sth->fetch(PDO::FETCH_ASSOC);
return $resultSet;
}
I have tried various different PDO::FETCH_... types but nothing is working. There is no information about what it is that I am supposed to send that part of the view.
If you want all the rows from fetch(), you will need to loop through the result set because it will return a single row. In the loop you can place them in an array.
You can use fetchAll() instead. It will return all the results as an array.

Putting data from database into variable using PHP (PDO, MVC)

Today I have looked all over the internet for a good answer. I almost got the answer from this site but that solution didn't work.
Here is what I need to do:
In the database there is a token stored that is going to be used for qr codes. I have already made something to generate the qr code when hardcoded:
$token_qr = "a86ad6352e939eea67da45b8731c3a8d62dcas1r";
$url_qr = some url;
$qr_code = array(
"token" => $token_qr,
"url" => $url_qr
); // end array
$qr_code_encoded = json_encode($qr_code, JSON_UNESCAPED_SLASHES);
$smarty->assign('qr_code_encoded', base64_encode($qr_code_encoded));
The base64 string is put in a url so the qr image can be generated.
Now I need to make it dynamically, the url is always the same but the token is always different. In the model where all the database statements are present I made this:
Class Webservices {
public function GetToken($token) {
$pdo = Database::Get();
$query = "SELECT `site__webservice`.* FROM `site__webservice` WHERE `token` = :token"; // SQL select statement
$params = array(":token" => $token); // bind params
$result = $pdo->Select($query, $params); // run query
// fetch token
if($result) {
$row = PDO::FETCH_ASSOC($result);
return $row[$token];
} else {
return false;
}
}
}
With this function I try to get the token from the database and store this in the $token_qr variable which stand in the controller. To call this I use this:
$webservices = new Webservices();
$token_qr = $webservices->GetToken($token);
The output of this function is now always false. Is there something wrong with my statement or is it in the loop that I created?
Maybe it is something really easy but I can't see the problem and find a solution for it. Thanks in advance for the response!
You need fetch the result before return, use fetch() or fetchAll(). Seems Select() works likes pdo execute() so it's return PDOStatment, fetch it to get the results.
if($result) {
$row = $result->fetchAll(PDO::FETCH_ASSOC);
return $row;

php function save result at array

hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>

unable to count the result with a condition using codeigniter query

I am trying to count rows of bookdetails table where display_id is as argument. Say i passed $id='3'. But i am not getting the output.
I think the code which i am trying is wrong. Please help me to write this query correctly
//--- Counting the rows of bookdetails of table where display_id is as argument-------------------------------------------------------------
public function record_count_for_secondtopBooks($id) {
$this->load->database();
return $this->db->count_all("bookdetails",array('display_id'=>$id));
}
count_all returns the number of rows in a particular
echo $this->db->count_all('my_table');
Try this
$this->db->where('display_id', $id);
$this->db->from('bookdetails"');
$this->db->count_all_results();
count_all accepts only one argument and that is table name. So you will get count of all records in that table. as written in manual:
Permits you to determine the number of rows in a particular table.
Submit the table name in the first parameter. Example:
$this->db->where('display_id',$id);
$result = $this->db->count_all("bookdetails");
or Chain em'
$result = $this->db->where('display_id',$id)->count_all("bookdetails");
check:
echo'<pre>';
print_r($result);
echo'</pre>';
Just try this,
$this->db->where('display_id', $id);
$query = $this->db->count_all('bookdetails');
return $query;
please try below code
public function record_count_for_secondtopBooks($id) {
$this->db->where('display_id',$id);
$q = $this->db->get('bookdetails');
return $q->num_rows();
}
try this
public function record_count_with_where($table_name,$column_name,$type)
{
$this->db->select($column_name);
$this->db->where($column_name,$type);
$q=$this->db->get($table_name);
$count=$q->result();
return count($count);
}

issue with my update-query

I'm trying to submit an update function, but for some reason it's not working and I can't figure out why... Someone who does?
UPDATE SQL-SYNTAX:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
PHP:
$project = new Project();
$project->name = $_POST['newproject_name'];
$project->photo1 = $_FILES['images']['name'][0];
if($project->updateProject($_DB, $projectname)) {
$feedback = "OK!";
} else {
$feedback = "NOT OK!!";
}
And in case you were wondering, $project->name and $project->photo1 are filled in correctly.
Any ideas? I hope I gave you everything you need, if not, let me know!
EDIT 1: I used the 2 first answers, but no results. Yet...
EDIT 2: I also don't get anything from $feedback
It looks like you have a stray opening parenthesis after the SET keyword. Remove it.
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
name = '".$db->escape($this->name)."',
photo1 = '".$db->escape($this->photo1)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
public function updateProject($db, $id)
requires 2 parameters being passed but when you do
if($project->updateProject($_DB))
you're only passing 1??
Your updateProject needs two variables and the second one is missing in your call, resulting in an invalid query.
Edit: Based on your edit; I'm guessing $id needs to be an integer or a string, you are passing an object.
Exactly what row do you want to update? I don't see anything in your php code that defines the ID of the row you want to modify, you are just generating a new object, not getting one from a database for example.

Categories