best way to do not redundant query? - php

I created the Rest API that are based on the MVC model. So far everything is working well but I want to find a clever way for the future when I'm 20 or 30 models that will communicate with the database. In particular, in every model functions should I write a query like this:
if($stmt = $connection->prepare("SELECT first_name FROM table WHERE id = ?"))
{
$id = 86;
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($res);
$stmt->fetch();
echo "My name is => " . $res;
$stmt->close();
}
which becomes annoying. How can I do something like CodeIgniter? I do not want to use external libraries or frameworks because I'm trying to learn how to build a base alone. Now I understand that this question probably does not fit fully into the community standards but I hope someone will understand that it is still a technical question.

To do so you can create a class that contains a class that can accept parameter to communicate with db as the way you want to do.
For example:
you can create a method like function getAll($table) which will return all rows of a the $table. Then you won't need to write same table fetching code again and again. You can just call getAll("users"); which will return all rows of your users table, or getAll('products);` which will return all rows of your 'product' table. I assume that the code inside those helper method won't be difficult for you.
Here is how you can make your given code less redundant.
function findFromTable($table, $id){
if($stmt = $connection->prepare("SELECT first_name FROM $table WHERE id = ?"))
{
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($res);
$stmt->fetch();
echo "My name is => " . $res;
$stmt->close();
}
}
Hope that will get you out or redundancy.

Related

android volly , get data from database row count [duplicate]

Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$userid = 1;
$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];
echo $username3;
This just looks like too many lines to get one value from the database. :\
You can use fetchColumn():
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();
You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
$q = $conn->prepare($sql);
$q->execute($parameters);
return $q->fetchColumn();
}
Then you can simply do:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
and it will get you the desired value.
So you need to create that function just once, but can reuse it for different queries.
This answer has been community edited addressing security concerns
Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.
All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.
If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.

How do I get only one value for the data I fetched from database using fetch function

I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable

Writing PDO DELETE query values

I was wondering if we can still use values from a freshly DELETE row as a SELECT or do we really need to SELECT it before ?
Example :
Transform this
$foo = $db->prepare("SELECT * FROM table WHERE id= :id");
$foo->execute(array(
"id" => $table_id
));
$foo = $foo->fetch(PDO::FETCH_ASSOC);
$delete_foo = $bdd->prepare("DELETE FROM table WHERE id = :id");
$delete_foo->execute(array(
"id" => $table_id
));
echo $foo['name'] . " has been deleted !";
Into this :
$delete_foo = $bdd->prepare("DELETE FROM table WHERE id = :id");
$delete_foo->execute(array(
"id" => $table_id
));
$delete_foo = $delete_foo->fetch(PDO::FETCH_ASSOC);
echo $delete_foo['name'] . " has been deleted !";
It would be easier. I was just wondering, I use the 1st method but it just went in mind and I don't find answers.
In postgresql, there is a proprietary extension to the delete statement called RETURNING. Sql Server provides something similar, they call it OUTPUT
For example, OUTPUT DELETED.* in the following DELETE statement
returns all columns deleted from the ShoppingCartItem table:
DELETE Sales.ShoppingCartItem
OUTPUT DELETED.*;
Unfortunately, mysql does not have anything like the above. If you delete a row it's gone (unless you roll back the transaction instead of commiting). If you want to Select the data, you need to execute the SELECT before the DELETE
DELETE queries wont return any results (besides rows affected), so a PDO::query wont have any usable data to fetch.
For the example provided, an extra select query just makes no sense. As you have your $value already.
I would rather say that you need to simplify your PDO code at whole. Compare the below code snippet with yours
$foo = $db->run("SELECT foo FROM table WHERE value = ?", [$value])->fetchColumn();
$db->run("DELETE FROM table WHERE value = ?", [$value]);
echo "$foo has been deleted!";
the run() function can be achieved by a very small PDO modification:
class MyPDO extends PDO
{
public function run($sql, $args = NULL)
{
$stmt = $this->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
the code is taken from my article, Simple yet efficient PDO wrapper

PDO : What´s the best method to get the result after insert data to database

I´m very new to PDO. I just wonder what´s the best way to get the result when the data insert to the database comletely. I´m looking around in googl. seems like it´s flexible. That makes me wonder what is correct and what is incorrrect way.
Let see example:
$sql = $conn->prepare("INSERT INTO tb_user(user_name, user_email) VALUES(:user_name,:user_email);
$sql->execute(array(':user_name'=>$user_name, ':user_email'=>$user_email));
$affected_rows = $sql->rowCount();
From this script I want to get result if the data is finish to be insert in database.
If it done-->I will echo it like "complete" and send it back to ajax or etc...
I have tried :
if($affected_rows){
echo"YEZZ!! complete";
}
And
$all = $slq->fetchAll();
if(count($all)) {
echo"YEZZ!! complete";
}
And
if ($sql->execute){
echo"YEZZ!! complete";
//this one i know it will double insert data to database because I called it twice//
But I still want to know when can I use this method
And maybe more ways out there which make me crazy and want to know what is the best way to get result if the thing is done:
AFter insert, after delete, after update these 3 statements is the most important to know each.
Any suggestions could be wonderful !
}
}
you could do:
$id = $conn->lastInsertId('IDCOLUMN');
and then execute a query and search for the id
$stmt = $conn->prepare("SELECT * FROM tb_user WHERE IDCOLUMN = :id");
$stmt->execute(array("id", $id);
if($stmt->rowCount() > 0) {
$result = $stmt->fetch(PDO::FETCH_ASSOC);
}
the result variable will contain your last inserted record
Yes, your approach with rowCount() is a right one. Stick with it.

return one value from database with mysql php pdo

Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$userid = 1;
$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];
echo $username3;
This just looks like too many lines to get one value from the database. :\
You can use fetchColumn():
$q= $conn->prepare("SELECT name FROM `login_users` WHERE username=?");
$q->execute([$userid]);
$username = $q->fetchColumn();
You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn() method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
$q = $conn->prepare($sql);
$q->execute($parameters);
return $q->fetchColumn();
}
Then you can simply do:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
and it will get you the desired value.
So you need to create that function just once, but can reuse it for different queries.
This answer has been community edited addressing security concerns
Just like it's far too much work to have to get into your car, drive to the store, fight your way through the crowds, grab that jug of milk you need, then fight your way back home, just so you can have a milkshake.
All of those stages are necessary, and each subsequent step depends on the previous ones having been performed.
If you do this repeatedly, then by all means wrap a function around it so you can reuse it and reduce it down to a single getMyValue() call - but in the background all that code still must be present.

Categories