Get data from database and pass to view - php

In controller I am trying to get data from table, and then pass it to the view.
//controller
public function view($id)
{
$contact = Contact::where('id', $id);
return view('contact.edit', ['contact' => $contact]);
}
//view
#foreach($contact as $key=>$value)
{{ $value }}
#endforeach
But I get just empty page, and if I try to echo value with {{ $contact->first_name}} i just receive error Undefined property: Illuminate\Database\Eloquent\Builder::$first_name.
I also tried to use find method, but got the same result.
Table schema:
CREATE TABLE `contacts` (
`id` int(11) NOT NULL,
`first_name` varchar(25) NOT NULL,
`last_name` varchar(25) NOT NULL,
`email` varchar(35) NOT NULL,
`home_phone` int(10) DEFAULT NULL,
`work_phone` int(10) DEFAULT NULL,
`cell_phone` int(10) DEFAULT NULL,
`best_phone` enum('home_phone','work_phone','cell_phone') NOT NULL,
`address_1` varchar(100) DEFAULT NULL,
`address_2` varchar(100) DEFAULT NULL,
`city` varchar(35) DEFAULT NULL,
`state` varchar(35) DEFAULT NULL,
`zip` int(6) DEFAULT NULL,
`country` varchar(35) DEFAULT NULL,
`birth_date` date DEFAULT NULL,
`manager` int(11) UNSIGNED NOT NULL
);

Contact::where('id', $id) only prepares a query with the query builder. You haven't yet executed the query or retrieved any results.
Contact::where('id', $id)->first() will execute the query and retrieve the first result, although since id is likely the primary key, Contact::find($id) is a quicker way to get the first result matching that id.

EDIT: Might be because you're not using ->first(); after the query.
Not really sure why that wouldn't work, you can try this instead:
public function view($id)
{
$contact = Contact::find($id);
return view('contact.edit')->with('contact', $contact);
}
Then in your view you can access all properties like so:
{{$contact->id}}
{{$contact->first_name}}
//etc

Related

I am trying to send post request from postman but at first request got accepted, but the data are stored as null

// mysql table creation
CREATE TABLE `users` (
`id` int NOT NULL,
`name` varchar(45) NOT NULL,
`gender` varchar(45) NOT NULL,
`designation` varchar(45) NOT NULL,
`address` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`cpassword` varchar(45) NOT NULL,
`age` int NOT NULL,
`phone` int NOT NULL,
`pincode` int NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
// Postman post request
{
"name":"krithi",
"age":15,
"gender":"female",
"phone":1234567890,
"designation":"volunteer",
"address":"chennai",
"pincode":90,
"password":"ac",
"cpassword":"ac",
"email":"abc#gmail.com"
}
// output in postman
{"code":1010,"message":"Data integrity violation"}
But it works well for get request. Any help would be much appreciated.
I changed my table into a simpler one
CREATE TABLE d (
name varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
and my json is`
{
"name" : "abc"
}
*and the response is*
{
"code": 9999,
"message": "Argument 1 passed to Tqdev\\PhpCrudApi\\Database\\ColumnsBuilder::quoteColumnName() must be an instance of Tqdev\\PhpCrudApi\\Column\\Reflection\\ReflectedColumn, null given, called in C:\\Users\\vimy9\\OneDrive\\Desktop\\clone\\php-crud-api\\api.php on line 4892"
}
You have id int NOT NULL in your query but you're not passing an ID while inserting, if you want it to be auto generated, it should be id int NOT NULL AUTO_INCREMENT.

CakePHP searching multiple models

I have a table called users and it is connected to coaches and clients.
I want to search in both users table and coaches table.
My tables look like this:
CREATE TABLE IF NOT EXISTS `team07`.`users` (
`id` INT(11) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(255) NOT NULL,
`usertype` CHAR(2) NOT NULL,
`created` DATETIME NOT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`firstname` VARCHAR(45) NOT NULL,
`lastname` VARCHAR(45) NOT NULL,
`phonenumber` VARCHAR(45) NOT NULL,
`suburb` VARCHAR(45) NOT NULL,
`state` VARCHAR(10) NOT NULL,
`businessname` VARCHAR(45) NULL DEFAULT NULL,
`image` BLOB NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_UNIQUE` (`email` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
And also
CREATE TABLE IF NOT EXISTS `team07`.`coaches` (
`id` INT NOT NULL,
`coachid` INT NOT NULL,
`appstate` INT NOT NULL,
`bio` VARCHAR(2048) NULL,
`price` INT NULL,
PRIMARY KEY (`id`),
INDEX `COACH_INFOFK_idx` (`coachid` ASC),
UNIQUE INDEX `coachid_UNIQUE` (`coachid` ASC),
CONSTRAINT `COACH_INFOFK`
FOREIGN KEY (`coachid`)
REFERENCES `team07`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
This is what the code I am doing looks like:
public function review()
{
//Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)
$users = $this->paginate($this->Users);
$users = $this->Users->find('all')->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);
$this->set(compact('users'));
$this->set('_serialize', ['users']);
}
However I am having issues because my page responds with
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'Coaches.appstate' in 'where clause'
How do I fix this?
If the association is understood by cake, you can use contain to load it:
https://book.cakephp.org/3.0/en/orm/query-builder.html#loading-associations
So something like this:
public function review()
{
//Select all users which are a Coach AND have appstate = 1 (Just signed up, in review)
$users = $this->paginate($this->Users);
$users = $this->Users->find('all')->contain(['Coaches'])->where(['Users.usertype'=>'CO', 'Coaches.appstate'=>'1']);
$this->set(compact('users'));
$this->set('_serialize', ['users']);
}

Laravel ManyToMany null id in where clause

I am having this same issue. Exactly the same issue accept different class and table names. Does anybody have some insight?
Site:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categoryBlocks()
{
return $this->belongsToMany(Category::class, 'blocked_category');
}
Category:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function sites()
{
return $this->belongsToMany(Site::class, 'blocked_category');
}
The query properly generates when querying from category to site but not from site to category. (I have tried renaming the method on the site Model but it doesn't help at all.)
$catBlocks = $category->sites()->get(); // Query creates a category_id value in the query
$blocks = $site->categoryBlocks()->get(); // Query doesn't create a site_id value in the query
Table: blocked_category
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`site_id` int(10) unsigned NOT NULL,
`category_id` int(10) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
Table: sites
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`publisher_id` int(10) unsigned NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`status_id` int(11) NOT NULL DEFAULT '1',
Table: categories
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
Try passing a third argument to the categoryBlocks relationship of 'category_id':
public function categoryBlocks()
{
return $this->belongsToMany(Category::class, 'blocked_category', 'category_id');
}
Or whatever you have called the category_id within the blocked_category table. If this doesn't work please reply with your database schema.
So I found the issue. The instance of the object being used to query wasn't being fully hydrated which was causing the query builder not to see the relationship properly.
I was getting the instance of the object passed into the method, but for some reason it wasn't a fully hydrated instance, so I just had to manually hydrate the Site object before running the query.

PDO update query runs changes no rows. No errors

So I'm running a PDO update working, and for some reason it won't update the table...
$business_id = 9874128;
$hidden = 1;
$query = "UPDATE business_property_overrides SET hidden=? WHERE business_id=?";
try {
$stmt = $pdo->prepare($query);
$stmt->execute(array($business_id, $hidden));
}
For some reason this won't update, even though I get no errors. The existing tables schema looks like this, and the data is:
There is an existing data set with business_id = 9874128 and hidden set to 0, but it won't update when I run the above code.
CREATE TABLE `business_property_overrides` (
`business_id` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(512) NOT NULL,
`apt_type` varchar(25) DEFAULT NULL,
`apt_num` varchar(9) DEFAULT NULL,
`street_address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`state` varchar(255) DEFAULT NULL,
`zip` varchar(25) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`url` varchar(512) DEFAULT NULL,
`hours` varchar(100) DEFAULT NULL,
`openhours` varchar(100) DEFAULT NULL,
`location` point DEFAULT NULL,
`yelp` varchar(512) DEFAULT '0',
`twitter` varchar(512) DEFAULT '0',
`hidden` tinyint(1) DEFAULT '0',
`merged` int(11) DEFAULT NULL,
`closed` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `business_id` (`business_id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9874134 DEFAULT CHARSET=utf8;
The hidden is TINYINT 1 characters long, you are assigning it business_id which is 7 characters long, that is the error.
Change
$stmt->execute(array($business_id, $hidden));
To:
$stmt->execute(array($hidden,$business_id))
As I've already commented over here, or you can simply use the placeholders of taking no care about the occurence like as
$query = "UPDATE business_property_overrides SET hidden = :hidden WHERE business_id = :business_id";
try {
$stmt = $pdo->prepare($query);
$stmt->execute(array(":business_id" => $business_id, ":hidden" => $hidden));
}

Create tables in database from queries in a text file

I have the following PHP page to create a table using a text file.
table_create.php
<?php
include $db;
$query_file = "sql.txt";
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
$retval = mysql_query($sql);
if(! $retval )
{
die("Could not create the tables<br>");
}
echo "Table created successfully<br>";
?>
sql.txt
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
CREATE TABLE ht_bank (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
ac_no varchar(50) NOT NULL,
address varchar(50) NOT NULL);
CREATE TABLE ht_user_role (
id int(11) NOT NULL AUTO_INCREMENT,
value varchar(50) NOT NULL);
When I try to create a single table in the sql.txt file, the code works perfectly.
For example:
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
But when I try to create multiple tables, It does not create any table. I doubt that the format in the sql.txt may be incorrect.
The format is, almost sure, correct but mysql_query doesn't work with multiple queries:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
It's better to use mysqli functions because mysql ones are deprecated for PHP 5.5 and mysqli has the function mysqli_multi_query that you need.
If you still want to use mysql functions you could do something like:
$sql_array=explode(';',$sql);
foreach ($sql_array as $s) {
if(! mysql_query($s)){
echo mysql_error()."<br>";
}
}

Categories