I have the following piece of Laravel Code:
public function remove($user_id)
{
//$result = $this->where('id','=',$user_id)->delete();
DB::transaction(function($user_id)
{
$item_subscriber = new ItemSubscriber();
$result = $this->where('id','=',$user_id)->delete();
$result = $item_subscriber->where('user_id','=',$user_id)->delete();
});
}
I am not getting clue the reason of this error.
Ok found out the mistake I was doing;I was not using use to pass parameter.
DB::transaction(function () use ($user_id)
{
$item_subscriber = new ItemSubscriber();
$result = $this->where('id','=',$user_id)->delete();
$result = $item_subscriber->where('user_id','=',$user_id)->delete();
Related
I am working on a website that uses PHP and SQL to connect to the database, I'm trying to replace all the SQL with Laravel Query Builder commands.
I am running into a problem with the following code:
public function queryUsers()
{
$db = $this->getMysql();
$stmt = $db->query("SELECT * FROM users");
while ($row = $stmt->fetch()) {
$this->addedUsers[$row['user_id']] = $row["slack_handle"];
$this->addedUserNames[$row['user_id']] = $row["name"];
}
}
I can easily connect to the database using Laravel, however I am not sure how to continue after the code shown below:
public function queryUsers()
{
$stmt = DB::table('users')->get();
}
TLDR:
In PHP/PDO Fetch fetches the next row from a result set, I'm curious if Laravel has an easy way to do the same.
public function queryUsers()
{
$users = DB::table('users')->get();
// $users is array of Std Object.
foreach($users as $key => $user) {
$data['user_id'] = $user->id;
// $user->name, $user->address
}
}
$users = DB::select('select * from users where active = ?', [1]);
foreach($users as $user){ ... }
https://laravel.com/docs/5.8/database#running-queries
I have the following function:
public function getUserMediaAction(Request $request)
{
$data = $this->decodeToken($request);
$username = $data['email'];
$user = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
->findOneBy(['email' => $username]);
$idUser = $user->getId();
$media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
->findNewbieAllData($idUser);
return new JsonResponse(['media' => $media->getPath()]);
}
findNewbieAllData:
public function findNewbieAllData($id_newbie)
{
$sql = "SELECT m
FROM ApplicationSonataUserBundle:User u
JOIN ApplicationSonataUserBundle:Media m
WHERE u.id=?1";
$query = $this->getEntityManager()
->createQuery($sql)
->setParameter(1, $id_newbie);
$result = $query->getArrayResult();
return $result;
}
which unfortunately returns the following error:
Call to a member function getPath() on array
Stack Trace
in src\CoolbirdBundle\Controller\UserController.php at line 97 -
$media = $this->getDoctrine()->getRepository('ApplicationSonataUserBundle:User')
->findNewbieAllData($idUser);
return new JsonResponse(['media' => $media->getPath()]);
}
Would anyone have any idea of how I can solve this problem, please?
thank you in advance
Try the following instead:
return new JsonResponse(['media' => $media[0]->getPath()]);
Edit: Looking at the var_dump output you should try this:
return new JsonResponse(['media' => $media[0]['path']]);
Method findNewbieAllData hydrates data with arrays.
$result = $query->getArrayResult();
return $result;
Look at getArrayResult method here:
https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php
Use getResult method instead.
I'm very new to PHP and Slim Framework which helps creating APIs.
Everything is ok If i query db inside $app->post or get. But I want to separate it to normal function. It will help when I need to use it later in other APIs.
I tried to call this
$app->get('/search/[{phone}]', function($request, $response, $args) use ($app){
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($token)){
return $this->response->withJson("valid");
}
return $this->response->withJson("invalid");
});
My isTokenValid() function
function isTokenValid($token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
But I get 500 Internal Server Error
Type: Error
Message: Call to a member function prepare() on null
File: /Applications/MAMP/htdocs/aigoido/src/functions.php
Line: 25
How to call it outside $app? Thanks.
You want to create a dependency injection container for your database connection and pass that object in as the function parameter rather than app object. This makes the db connection reusable throughout your app.
https://www.slimframework.com/docs/concepts/di.html
Also, you can return $response rather than $this->response.
$c = $app->getContainer();
$c['db'] = function() {
return new DB($host,$user,$pass,$name);
};
$app->post('/search/[{phone}]', function($request, $response, $args) use ($c) {
$token = $response->getHeader('token');
// $phone = $args['phone'];
if (isTokenValid($c->db,$token)){
return $response->withJson("valid");
}
return $response->withJson("invalid");
});
function isTokenValid($db, $token){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $db->prepare($sql);
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
Pass $app to your function as parameter. The function has it own context so $app is not available without that.
function isTokenValid($token, $app){
$sql = 'SELECT id FROM users WHERE token = :token';
$s = $app->db->prepare($sql); //<< this line 25
$s->bindParam(':token', $token);
if ($s->execute()){
if($sth->rowCount() > 0){
return true;
}
}
return false;
}
I'm working on a project. how to calculate comment by id?
example
controler:
public function comments() {
$id_alat = $this->db->where('id_alat');
$com = $this->mcrud->getComent($id_alat);
$com = $this->mcrud->getComent($id_alat);
$data = array (
'com' => $com,
'content' => 'instrument/instrument');
$this->load->view('layouts/wrapper', $data);
}
models:
public function getComent($id_alat) {
$sql = "SELECT count (*) as num FROM WHERE tbcoment $id_alat tbcoment.id_alat = {}";
$this->db->query($sql);
}
view:
comments: <?php echo $com; ?>
Use following code for model
Your Model
public function getComent($id_alat)
{
$sql = "SELECT count (*) as num FROM WHERE tbcoment.id_alat = '$id_alat'";
$res=$this->db->query($sql)->row_object();
return $res->num;
}
Note: Don't use spaces inside php tags and variables.
Ex01: $ id_alat should come $id_alat
Ex02: $ this-> mcrud-> getComent ($ id_alat); should come $this->mcrud-> getComent($id_alat);
Code Example
In controller
function comments () {
$id_alat = '';//Asign data to here
$data['com'] = $this->Model_name->getComent($id_alat);
$data['content'] = 'instrument / instrument';
$this->load->view ('layouts/wrapper', $data);
}
In Model
function getComent($id_alat) {
$query =$this->db->query("SELECT * FROM table_name WHERE tbcoment='$id_alat'");//cahnge table name, and argument that you want
$result = $query->result_array();
$count = count($result);
return $count;
}
In view
comments: <?php echo $com; ?>
you can also use this code:
$this->db->where('id',$id)
->from('table_name')
->count_all_results();
this can be used either on MVC(Model, View, Controller);
you can find this code on the user guide
this may be a stupid question, but every source on the web seems not able to fully explain the logic to my complex brain
There's an edit page getting a $_GET['id'] from a link.
I got a function on my class elaborating this one to create an array of values from the database which must fill the form fields to edit datas. The short part of this code:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from anammi.anagrafica WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
This array (which i tried to print) is perfectly ready to do what i'd like.
My pain starts when i need to pass it to the following function in the same class, which perhaps calls a parent method to print the form:
public function Associa() {
$a = $this->EditDb();
$this->old_id = $a['old_id'];
$this->cognome = $a['cognome'];
$this->nome = $a['nome'];
$this->sesso = $a['sesso'];
$this->tipo_socio_id = $a['tipo_socio_id'];
$this->titolo = $a['titolo']; }
public function Body() {
parent::Body();
}
How do i have to pass this $fetch?
My implementation:
<?php
require_once '/classes/class.ConnessioneDb.php';
require_once '/classes/class.editForm';
$edit = new EditForm();
$edit->prel();
if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();
if (if ($edit->EditDb()) {
$edit->Associa();
$edit->Body();) {
$edit->Associa();
$edit->Body();
your Editdb method is returning a string and you are checking for a boolean condition in if statement. this is one problem.
using fetch-
$fetch=$edit->EditDb();
$edit->Associa();
$edit->Body($fetch);
Posting the full code of it:
public function prel() {
$this->id= $_GET['id'];
}
public function EditDb () {
$connetti = new connessionedb();
$dbc = $connetti->Connessione();
$query = "SELECT * from table WHERE id = '$this->id'";
$mysqli = mysqli_query($dbc, $query);
if ($mysqli) {
$fetch = mysqli_fetch_assoc($mysqli);
return $fetch;
}
}
public function Associa($fetch) {
$this->old_id = $fetch['old_id'];
$this->cognome = $fetch['cognome'];
$this->nome = $fetch['nome'];
$this->sesso = $fetch['sesso']; //it goes on from there with many similar lines
}
public function Body() {
$body = form::Body();
return $body;
}
Implementation
$edit = new EditForm();
$edit->prel();
$fetch=$edit->EditDb();
$edit->Associa($fetch);
$print = $edit->Body();
echo $print;
Being an edit form base on a parent insert form, i added an if in the parent form that sees if is set an $_GET['id] and prints the right form header with the right form action. This was tricky but really satisfying.