Jump to content

jiros1

Members
  • Posts

    25
  • Joined

  • Last visited

Everything posted by jiros1

  1. Hi Ignace, thanks to your hint I've made the following changes and got it working: GameType: $builder ->add('name', TextType::class, [ 'attr' => [ 'class' => 'form-control', ], ]); $builder ->add('type', EntityType::class, [ 'class' => 'AppBundle:Type', 'choice_label' => function ($type) { return $type->getName(); }, 'multiple' => false, 'expanded' => false, 'attr' => [ 'class' => 'form-control', ], ]); game/show.html.twig <table> <tbody> <tr> <th>Name</th> <td>{{ game.name }}</td> </tr> <tr> <th>Type</th> <td> {% if game.type is not null %} {{ game.type.name}} {% endif %} </td> </tr> </tbody> </table>
  2. Thanks for the reply, but by now I'm already using that. I've changed my code so I want to edit my original post, now I'm looking for the edit button... How silly is that I now have selectbox but it replaced my exisiting textfield, I think I know why that is, textfield holds the value for Game.name but the newly added selectbox holds the value of type.name. GameType.php public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add( 'name', EntityType::class, [ 'class' => 'AppBundle:Game', 'choice_label' => 'name', 'label' => 'name' ] ); $builder ->add( 'name', EntityType::class, [ 'class' => 'AppBundle:Type', 'choice_label' => 'name', 'multiple' => false, 'expanded' => false ] ); } Could it be that it has something to do with the same property, name?
  3. Hi! For a form I would like to render a selectbox with values from another relation: Type. This is a many-to-one relation, owned by Type. Type has many Games, while Game has one Type My question is, how do I show a selectbox with values from Type? e.g: Game: Monopoly Select Type: (selectbox) - Party game - Strategy - Co-op - etc. ----------------------------------------------- This is what I have: GameType.php <?php namespace AppBundle\Form; use AppBundle\Entity\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class GameType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name'); $builder ->add( 'types', choiceType::class, [ 'class' => 'AppBundle:Type', 'choice_label' => 'name', 'multiple' => false, 'choices_as_values' => true, 'expanded' => true ] ); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'types' => [], 'data_class' => 'AppBundle\Entity\Game' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'appbundle_game'; } } Entity/Game.php <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * Game * * @ORM\Table(name="game") * @ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository") */ class Game { /** * @ORM\ManyToOne(targetEntity="Type", inversedBy="games") * @ORM\JoinColumn(name="type_id", referencedColumnName="id") */ private $type; /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, unique=true) */ private $name; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Game */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * @return mixed */ public function getType() { return $this->type; } /** * @param mixed $type */ public function setType($type) { $this->type = $type; } } Entity/Type.php <?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; /** * Type * * @ORM\Table(name="type") * @ORM\Entity(repositoryClass="AppBundle\Repository\TypeRepository") */ class Type { /** * @ORM\OneToMany(targetEntity="Game", mappedBy="type") */ private $games; public function __construct() { $this->games = new ArrayCollection(); } /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name * * @return Type */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * @return mixed */ public function getGames() { return $this->games; } /** * @param mixed $games */ public function setGames($games) { $this->games = $games; } } I'm starting out with Symfony, any help is greatly appreciated!
  4. Thanks for your quick reply, Jacques1, it looks a lot better now thanks to you: const DB_HOST = 'yourhost'; const DB_USER = 'user'; const DB_PASSWORD = 'pswd'; const DB_NAME = 'db'; const DB_CHARSET = 'UTF8'; $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET; $databaseConnection = new PDO($dsn, DB_USER, DB_PASSWORD, [ PDO::ATTR_EMULATE_PREPARES => false, // important: Disable emulated prepared statements: PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); class Model { protected $databaseConnection; public function __construct(PDO $databaseConnection){ $this->databaseConnection = $databaseConnection; } } class user extends Model { public function getAll(){ $sql = "SELECT name FROM users"; $stmt = $this->databaseConnection->query($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); return $result; } } $user = new user($databaseConnection); $getAllUsers = $user->getAll(); foreach($getAllUsers as $row){ echo $row['name']; } Also, thanks for the reminder:
  5. Awesome, thanks!
  6. I want to clean up my code by inheriting the database class so I can connect from any class that wants to inherit the database connection. I'm not sure this is the right way but I thought about fixing this by inheriting the __construct function, but how would I call it in this example? Currently I have this; it works, but could this be improved? Or is there a better, cleaner way to do this? $pdo = parent::__construct(); My code: class database { function __construct(){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "temp"; $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } } class user extends database { public function getAll(){ $pdo = parent::__construct(); $sql = "SELECT name FROM users"; $stmt = $pdo->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); return $result; } } $user = new user; $getAllUsers = $user->getAll(); foreach($getAllUsers as $row){ echo $row['name']; }
  7. Thanks a lot, I've got it working now! A question though, how come we can do a foreach iteration now? And why doesn't that work for MYSQLi?
  8. Hi, Thanks for taking the time. I'm trying PDO for the first time and I'm trying to make a CRUD codebase. I can insert but I have trouble with the select statement and iterate through the data, Apache gives me this error: Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean in index.php:38 This is line 38: $getName = $result; while( $row = $getName->fetch_assoc() ){ echo $row['name']; } This is my code: $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT name FROM users"); $stmt->execute(); // set the resulting array to associative $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); $getName = $result; //Iterate through the data // line 38: while( $row = $getName->fetch_assoc() ){ echo $row['name']; }
  9. It appears that the condition is set right, because if I work with only strings then it works just fine. But when I return null or an array then it doens't work... I just can't get my head around this, what am I missing? //If the visitors can't fit in the gap of available seats. if($visitors<$gap){ //$result = false; $result = "doesn't fit"; } else{ //$result = $seats; $result = "it fits"; } return $result;
  10. I'm trying to make a function that checks if there are enough seats available for visitors. If there's enough room for the visitors, return an array with suggested seats, else return null. Method: I'm making a gap, this gap will be increased by 1 everytime there is a available seat. At the end of my function, I compare if the $visitors fit in the $gap, if they don't return null and if they do, return the array. The problem: My function returns an array even though there's not enough room. My question: How do I let my function return null if there are not enough seats? This is my code: <?php error_reporting(E_ALL & ~E_NOTICE); $visitors = 6; $seats = array( array( 'seatAvailable' => '0', 'seatNumber' => '1' ), array( 'seatAvailable' => '0', 'seatNumber' => '2' ), array( 'seatAvailable' => '1', 'seatNumber' => '3' ), array( 'seatAvailable' => '1', 'seatNumber' => '4' ), array( 'seatAvailable' => '1', 'seatNumber' => '5' ), ); $gap = 0; echo "Visitors: ".$visitors; echo "<ol>"; function suggestSeats($seats,$visitors){ foreach($seats as &$val){ //If available if($val['seatAvailable'] == '1'){ //If there's no gap, start making one now: if($gap<1){ $gap = 1; } $gap++; //IF THERE ARE STILL VISITORS TO PROCESS, MARK THE SUGGESTED SEAT if($visitors > 0) { $val['seatAvailable'] = 'x'; $visitors--; } } //IF THERE ARE NO MORE VISITORS, EXIT LOOP if($visitors == 0) { break; } } //echo "gap".$gap; //If the visitors don't fit in the gap of available seats. if($visitors>$gap){ $result = null; } else{ $result = $seats; } return $result; } echo "</ol>"; echo "<pre>"; print_r (suggestSeats($seats,$visitors)); echo "</pre>"; ?> This is the output of my script as it is now: Visitors: 6 Array ( [0] => Array ( [seatAvailable] => 0 [seatNumber] => 1 ) [1] => Array ( [seatAvailable] => 0 [seatNumber] => 2 ) [2] => Array ( [seatAvailable] => x [seatNumber] => 3 ) [3] => Array ( [seatAvailable] => x [seatNumber] => 4 ) [4] => Array ( [seatAvailable] => x [seatNumber] => 5 ) ) I want it to show null instead of returning the array.
  11. There are seats that need to be assigned to visitors, for each visitor I check if the seat is available, if it is, give the value 'x' for 1 $visitor until there are no visitors left. I want to execute a line of code for x times, x = the value of visitors. As the code is now, I want to suggest 2 visitors a seat by giving the value 'x'. I will use the values as follows: 1 = available 0 = is not available x = was available, and now it's a suggested seat The problem: I want to have a output of two X's, but as the script is now, it generates three X's, and I don't know why. The question: How do make my script so that it will output two X's (the value of $visitors)? The output: Visitors: 2 Array ( [0] => Array ( [seatAvailable] => 0 [seatNumber] => 1 ) [1] => Array ( [seatAvailable] => 0 [seatNumber] => 2 ) [2] => Array ( [seatAvailable] => x [seatNumber] => 3 ) [3] => Array ( [seatAvailable] => x [seatNumber] => 4 ) [4] => Array ( [seatAvailable] => x [seatNumber] => 5 ) ) My code <?php $visitors = 2; $seats = array( array( 'seatAvailable' => '0', 'seatNumber' => '1' ), array( 'seatAvailable' => '0', 'seatNumber' => '2' ), array( 'seatAvailable' => '1', 'seatNumber' => '3' ), array( 'seatAvailable' => '1', 'seatNumber' => '4' ), array( 'seatAvailable' => '1', 'seatNumber' => '5' ), ); echo "Visitors: ".$visitors; echo "<ol>"; foreach($seats as &$val){ //If not available if($val['seatAvailable'] == '0'){ //echo "<li>not available</li>"; } //If available elseif($val['seatAvailable'] == '1'){ //Give available spots the value X, for as many as there are $visitors for($i=0;$i<$visitors;$i++){ $val['seatAvailable'] = 'x'; } } } echo "</ol>"; echo "<pre>"; print_r($seats); echo "</pre>"; ?>
  12. @Gizmola, based on your example I have made a script that runs through the seats and makes gaps along the way. It checks if the provided quantity of visitors fit in the gaps. My question is how do I make it so that it executes only the first gap? current output: 3 visitorsit fits123Seat: 1(gap size: 5) it fits111213Seat: 11(gap size: 5) It starts at the first available seat from there it increments by one until it reaches the quantity of visitors. This is one gap. This is my code: functions.php <?phpfunction connectDB(){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "movie-theatre"; $connection = new mysqli($servername, $username, $password, $dbname); if ($connection->connect_error){ die("Connection failed: " . $connection->connect_error); } else{ return $connection; } } function fetchSeats(){ connectDB(); $sql = "SELECT seats.* FROM seats "; $result = connectDB()->query($sql); return $result; } function suggestSeats($startingSeatNumber,$quantity) { for($x=0; $x < $quantity; $x++) { echo $startingSeatNumber; $startingSeatNumber++; } } ?> index.php <?php// Report all errors except E_NOTICE error_reporting(E_ALL & ~E_NOTICE); include "functions.php"; connectDB(); //$seatsAvailable = []; $seatReservation = []; $gap = 0; $visitors = 3; // $start = 0; $seatNumber = ""; $seats = fetchSeats(); echo "<h2>".$visitors." visitors</h2>"; while($seat = $seats->fetch_assoc()){ //seat available if($seat['seatAvailable']){ //when there's no gap set the current seatnumber and increment the gap size //so we know how much capacity there is for the visitors. if($gap == 0){ $seatNumber = $seat['seatNumber']; } $gap++; } //seat taken else{ //If there's a gap if($gap > 0){ //If the quantity of visitors fit in the gap if($visitors <= $gap){ echo "it fits"; suggestSeats($seatNumber,$visitors); echo "<strong>Seat: ".$seatNumber. "(gap size: ".$gap. ")</strong></br>"; } // $start = 1; $gap = 0; $seatNumber = ""; } } } if($gap > 0) { if($visitors <= $gap){ echo "it fits"; suggestSeats($seatNumber,$visitors); echo "<strong>Seat: ".$seatNumber. "(gap size: ".$gap. ")</strong></br>"; } //echo "<strong>Seat: ".$seatNumber. "(gap size: ".$gap. ")</strong>"; } ?>
  13. You can download the Windows version of Composer on the same link you provided. This setup file takes care of everything and if you enable shell menu during setup, you can right click on a folder and use composer directly in that folder. A box shows up where you can enter commands, this is a terminal. I use it too and it's very easy to use.
  14. Thanks for the quick replies! @Barand, I don't need the rows, the seats are only defined as seat numbers, but I understand why you would think that. @Gizmola, your "$gaps[]" approach looks very interesting and might just be what I need. I get a vague idea of your theory but I don't how to actually make this. Can you please elaborate how I can implement your idea? $gaps[] = array('start' => 1, 'end' => 4, 'count' => 4);
  15. Thank you for taking the time to read this. I have an excercise where I need to build a small part of seat reservation system for a movie theatre. Seats are assigned to guests who want to reserve tickets. As input I receive a quantity of visitors and as output I need to return a array with the reserved seatnumbers. Everyone needs to sit close to each other as possible. I have to think about making a script where I look into the list of seats where there’s room for the quantity of visitors. There are only seat numbers (not rows) so I only have to make sure that the seatnumbers are assigned to the guests as close as possible. I need to fit the number of visitors in between the seats that are already taken. If there are more seats available then I have to assign the lowest seatnumber. If there is no room for the visitors to sit to each other then I have to look elsewhere, where to fit them. E.g: if there is no room for 7 visitors to each other then I have to find a place where there can be 6 and the 7th will sit elsewhere. If it’s not possible I’ll return null instead of the array. To start off: what is the best php function to look for any room into an array and make a new array from the results? E.g: seatnumbers 1-4 are available and 5-8 are taken. My script will find room for my 4 visitors and will assign seatnumbers 1-4 and present this as a new array. This is my code: <?php function DBConnect(){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "movie-theatre"; $connection = new mysqli($servername, $username, $password, $dbname); if ($connection->connect_error){ die("Connection failed: " . $connection->connect_error); } else{ return $connection; } } function giveSeatNumbers($visitors){ $seats = array(); echo "<ol>"; for($x = 1; $x < $visitors+1; $x++){ array_push($seats,$x); } echo "</ol>"; /* within the list, try to fit the visitors in the seats array, each visitor must get one seat, if available, starting with the lowest value. */ } function getSeats(){ DBConnect(); $sql = "SELECT seats.* FROM seats WHERE seats.Available = 1; "; $result = DBConnect()->query($sql); return $result; } $seats = getSeats(); echo "Seats from database:"; for($x=0; $x<5; $x++){ while($seat = $seats->fetch_assoc()) { echo $seat['seatNumber']; } } //This is where I define the number of visitors $quantityVisitors = 10; giveSeatNumbers($quantityVisitors); ?> <p> Quantity of tickets ordered: <?php echo $quantityVisitors;?> </p> <p> The following seats will be assigned to you: </p>
  16. If your CSS files are not loaded properly then Laravel doesn’t know where to look for them. To let Laravel know where your CSS file is located you’ll need to set a direct path in your blade file: {!! HTML::style('_asset/css/custom.css') !!} It looks very similar for javascript files: {!! HTML::script('_asset/js/jquery.min.js') !!} If this doesn’t work, or you’ll get an error that the HTML serviceprovider class is missing, you’ll need to install the illuminate/html package. This is how you do it: Add the following line in the require section of composer.json file "require-dev": { "illuminate/html": "5.*", And run composer update. Register the service provider in config/app.php by adding the following value into the providers array: Illuminate\Html\HtmlServiceProvider::class And finally register the facades by adding these two lines in the aliases array: 'Form'=> 'Illuminate\Html\FormFacade', 'HTML'=> 'Illuminate\Html\HtmlFacade'
  17. Thanks for the reply, I was trying this in Laravel and it didn't work, now I've fiddled with it in "vanilla" PHP and now it works. I guess it was too soon for me to try something in a framework I haven't done yet.
  18. I'm trying to make a basic filter script for editing my games with str_replace. I want to censor bad words with str_replace, but it's not working, it just returns the original input. This is the contents of my function, it's activated when I submit the form: $game = Game::findOrFail($id); $filtered_game = str_replace('thefword', 'f***', $game); echo $filtered_game; $game contains an array with 1 item: {"id":18,"name":"Dragonball3","category_id":2,"user_id":1,"created_at":"2015-12-03 11:35:04","updated_at":"2015-12-03 11:35:44","gamegroup_id":0} The original game name is "dragonball3", when I put in the "F" word, my string won't be returned as "f***" but still as Dragonball3. This function is originally intended for the edit functionality, which works perfectly but I have disabled this for testing purposes. The output I want is this: {"id":18,"name":"f***","category_id":2,"user_id":1,"created_at":"2015-12-03 11:35:04","updated_at":"2015-12-03 11:35:44","gamegroup_id":0} Maybe there is a better way? I want to fix this but I think it's more important that I learn from this.
  19. Thank you for answering my question, based on your solution I now have this code and it works like a charm: $Game_Name = $_POST['Game_Name']; $Game_ID = $_POST['Game_ID']; $Category_ID = $_POST['Category_ID']; //query $sql = "UPDATE TBL_Game SET Category_ID =?, Name =? WHERE TBL_Game.ID =? "; $statement = $db -> prepare($sql); $statement -> execute(array( $Category_ID, $Game_Name, $Game_ID, )); Only thing left now is make it an object so my code is more maintainable. Thanks!
  20. Thank you for your time. I'm trying to update a Game in my database, I'm new with PDO. I can edit the name but I don't know how to change the category. I select it from the table TBL_Category where TBL_Category.ID equals JTBL_Game_Category.Category_ID. How do I update it via a dropdown box so my Game's Category is changed? This is my PHP code: $Name = $_POST['Name']; $id = $_POST['ID']; $sql = "UPDATE TBL_Game SET Name=? WHERE id=?"; $statement = $db -> prepare($sql); $statement -> execute(array($Name, $id)); header("Refresh:0"); My tables: TBL_Game ID= 1 Name= Game of thrones TBL_Category ID= 1 Name= Boardgame JTBL_Game_Category ID 1 Game_ID= 1 Category_ID= 1 Thanks in advance
  21. Thanks guys, it works now, and more importantly, I know why! Thank you for the elaborate explanations!
  22. Hi Ch0cu3r, It works now and thank you for going through the steps of explaining to me what I was doing wrong, it's nice to get my code working but even better to learn from it. In the second part you handed me some material to think about improving my database connections, It looks great the way you do it, but it's not working for me. My guess is that I'm doing something wrong here: It gives me the following errors: Warning: Missing argument 1 for Game::__construct() Notice: Undefined variable: db in manage-games.php Notice: Undefined variable: db in Game.php Fatal error: Call to a member function prepare() on a non-object in Game.php My current updated Game.php model: <?php require "include/dbconnect.php"; class Game { public $ID = ""; public $Name =""; private $db; function __construct($db){ $this->db = $db; } public function getAll(){ $this->db; //require "include/dbconnect.php"; $sql = "SELECT * FROM TBL_Game"; $query = $db->prepare($sql); $query->execute(); $result = $query->fetchAll(); return $result; } } My current updated manage-games.php view: <?php $Game = new Game; $Game = new Game($db); $result = $Game->getAll(); foreach($result as $row){ echo $row['Name'] . '<br />'; } ?> Thanks in advance!
  23. Greetings, thank you for taking the time and reading my question. I'm trying to use PDO for the first time within a object and I'm trying to iterate through my array and displaying the right record (Game in this case). This is the error I get: Fatal error: Call to a member function getAll() on a non-object in /media/sf_sandbox/boardgame-collection/view/manage-games.php on line 34 And this is what I want: Descent second edition World of Warcraft the boardgame Here is the code of my model: The Game model class Game { public $ID = ""; public $Name =""; public function getAll(){ require "include/dbconnect.php"; $sql = "SELECT * FROM TBL_Game"; $query = $db->prepare($sql); $query->execute(); $result = $query->fetchAll(); return $result; } } Now I'm trying to get it by doing this: manage-games.php <?php require "model/Game.php"; $Game = new Game; $Game = $Game->getAll(); while($Game = $Game->getAll()){ echo $Game->Name; } ?>
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.