PHP - Frustrating Mistake...
I was just about to post a problem which I have been working on for 2 days... and the spell check in the text box pointed out that my variable missing a freaking T...... I dont know about you guys but I will defo run my code through a spell checker now....
I hope you are all having a nice day =) Similar TutorialsHi there, First of all, I want to present the diagram that I'm working on. ----------- Diagram ----------- step2_a.php --| step2_b.php --|---> output.php step2_c.php --| (Process is included here) step2_d.php --| and here are the corresponding codes: step2_x: Code: [Select] . . . <form action="output.php" method="post" name="a"> req1: <input type="text" name="a_req_1"> req2: <input type="text" name="a_req_2"> . . . <input type="submit"> </form> ------ . . . <form action="output.php" method="post" name="b"> req1: <input type="text" name="b_req_1"> req2: <input type="text" name="b_req_2"> . . . <input type="submit"> </form> . . . . . . output.php: Code: [Select] <?php $form_name = $_POST['a']; if($form_name = "a") { //variables for a goes here //code goes here } elseif($form_name = "b") { //variables for b goes here //code goes here } elseif($form_name = "c") { //cariables for c goes here //code goes here } elseif($form_name = "d") { //variables for d goes here //code goes here } else { //code goes here } ?> Now, here's the problem. output.php always sees the primary condition as true. Even the data came from step2_b, the code does not recognize it. I tried to use "==" instead of "=" but the code sees the arguments as false so it executed the code on "else". How can I make the code distinguish the source of the data so that it would execute the right set of commands? Thanks in advance. Hello everyone.
Bear with me here, I'm not a true PHP or otherwise coder by trade and have only a basic understanding of the terminology. I'll try to explain my issue as clearly as I can.
I'm working with a Wordpress theme. The "WP Conference Theme" to be exact.
This theme allows you to quickly and easily add Speakers to your conference by way of an automated form. When you create a new speaker, you have the option to create a new "role" for them. This can be anything you want, such as "moderator", "host, "panelist" - what have you.
Picture 1:
In the general settings for the conferece, there is a dropdown where you have the option to select a "role" of speaker to display on the footer of the homepage - additionally, the category of speaker selected here is used to populate a stand-alone page showcasing all the speakers. Every speaker assigned the selected role appears in both these locations. Here is a shot of the HTML from the source code of this dropdown:
Here you can see the default role "Speaker" and the new role I have created, "whyattend".
Currently the footer and speaker page show whichever "role" is selected from the dropdown in the general settings.
I want to show one category of speaker in the footer (whyattend), and have an entirely different category show on the speaker page (Speaker).
Since the Speaker page populates automatically by way of the role selected in the general settings, I started with the code for the Footer.
Here is the PHP for the Footer:
I have tried playing around with this already and have gotten results CLOSE to what I am looking for, but not quite.
The closest I came was by changing the last instance of "('role'=>$speaker" to "('role'=>$whyattend".
Doing this shows ONLY those desginated as "speakers" on the Speaker page, but it still shows all of the roles on the footer.
The PHP on the Speaker page is identical to this code on the footer.
I apologize if this is confusing.
i have been pondering how you would set this scenario up for a while. such as on this site, with private messages, and the inbox; how would you create a database that will hold the messages, and their sender, date, other data, etc.? lets say i send message 1: "hello there!", then 2: "how are you doing?". when this goes into the database, so i can later echo this on the member's index page, how would i organize, and echo these messages? no detailed code needed, just need "pseducode"/something to think about. what would be the best way? separate messages by commas? Having an issue with this code, there are 3 parts and it is a simple guestbook type thing. But my problem is that it worked the first time I signed the guestbook but now its saying Unable to create the table. Error code 1050: Table 'visitors' already exists << I know it already exists but WHY is it trying to create it again? << Heres the code Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Guest Book</title> </head> <body> <?php if (empty($_GET['first_name']) || empty($_GET['last_name'])) die("<p>You must enter your first and last name! Click your browser's Back button to return to the Guest Book form.</p>"); $DBConnect = @mysqli_connect("localhost", "***********", "***********") Or die("<p>Unable to connect to the database server.</p>" . "<p>Error code " . mysqli_connect_errno() . ": " . mysqli_connect_error()) . "</p>"; $DBName = "guestbook"; if (!@mysqli_select_db($DBConnect, $DBName)) { $SQLstring = "CREATE DATABASE $DBName"; $QueryResult = mysqli_query($DBConnect, $SQLstring) Or die("<p>Unable to execute the query.</p>" . "<p>Error code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) . "</p>"; echo "<p>You are the first visitor!</p>"; mysqli_select_db($DBConnect, $DBName); } $TableName = "visitors"; $SQLstring = "SELECT * FROM $TableName"; if (!$QueryResult) { $SQLstring = "CREATE TABLE $TableName (countID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY, last_name VARCHAR(40), first_name VARCHAR(40))"; $QueryResult = mysqli_query($DBConnect, $SQLstring) Or die("<p>Unable to create the table.</p>" . "<p>Error code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) . "</p>"; } $LastName = addslashes($_GET['last_name']); $FirstName = addslashes($_GET['first_name']); $SQLstring = "INSERT INTO $TableName VALUES(NULL, '$LastName', '$FirstName')"; $QueryResult = mysqli_query($DBConnect, $SQLstring) Or die("<p>Unable to execute the query.</p>" . "<p>Error code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) . "</p>"; echo "<h1>Thank you for signing our guest book!</h1>"; mysqli_close($DBConnect); ?> </body> </html> Can someone please point my to the right direction. Getting frustrated and I am assuming it is something quite simple i am overlooking. Thanks in advance. I'm calling a function that resets a couple arrays: public function resetStuff() { $this->someArray = array(); $this->someOtherArray = array(); } However, someOtherArray is not resetting!! How could that be? I can add debug statements to echo the size of the arrays before and after the function calls. It shows that: someArray went from n to 0 someOtherArray went from n to n How is that possible?? But where???
I have set up a script for people to remove themselves from a mailing list.
It worked fine so far, but when I added a possibility to show a message the entered email addres did not exist, things went wrong.
The script still runs, there are no errors, but when the user enters a non-existing email address, it still says "You have been removed".
Everything seemed to go well until I added a button to a URL (echo'd) rather than a plain link.
I have checked and rechecked, re-examined the flow, but I cannot find where I went wrong.
One further thing: the people get sent to this page by a one field form on a HTML page, with method "post".
Anyway, here is the script:
<HTML> <HEAD> <TITLE>Vlaanderen-Flanders</TITLE> </HEAD> <BODY> <?php // Always try to connect and select the DB before anything else $con = mysql_connect("localhost","jingleko_reload","*******") or die("Couldnt Connect to DB - ".mysql_error()); mysql_select_db("jingleko_reloader", $con) or die("Couldnt Select a DB - ".mysql_error()); // Set post var $Epost = trim(addslashes(strip_tags($_POST['Epost']))); // Look for it in DB $query = "SELECT Epost FROM newsletter WHERE Epost='".$Epost."'"; $result = mysql_query($query); //If found, do next thing if(isset($_POST['Epost'])) { mysql_query("DELETE FROM newsletter WHERE Epost='$Epost'") or die (mysql_error()); echo "<div align=\"center\"><img src=\"Pics/Vlaamse Leeuw.jpg\" width=\"114\" height=\"127\" border=\"0\"></div>"; echo "<p align=\"center\"><b>Thank you, you are now removed from the list.</b></p><br>"; echo "<p align=\"center\"><a href=\"index.htm\"><img src=\"Pics/begin.gif\" width=\"95\" height=\"30\" border=\"0\"></a></p>"; } else { echo "<div align=\"center\"><b><font color=\"red\">This address does not exist</font></b></div><br>"; echo "<div align=\"center\"><a href=\"eruit.htm\"><img src=\"Pics/herbegin.gif\" width=\"95\" height=\"30\" border=\"0\"></a>"; echo "<a href=\"index.htm\"><img src=\"Pics/begin.gif\" width=\"95\" height=\"30\" border=\"0\"></a></div>"; } mysql_close($con); ?> </BODY> </HTML>Any ideas, please? Sometimes when I altered the code, I just got a blank page. Thanks in advance. When I try to echo the values selected in my select boxes ( $first and $last ) nothing shows up.... I'm wondering if my user created function isn't naming them like I'd like... <html xmlns="http://www/w3c.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Catherine: TV Test</title> <script type="text/javascript"> function load() { var wH = window.innerHeight; var wW = window.innerWidth; document.getElementById('windowWidth').setAttribute('value',wW); document.getElementById('windowHeight').setAttribute('value',wH); } </script> <style type="text/css"> #main { position: relative; height: 100%; margin-left: 20px; margin-right: 20px; } table { position: relative; top: 20px; margin-left: auto; margin-right: auto; text-align: center; } <?php echo '#leftbar { position: absolute; top: 20px; left: 0px; width: 50%; height: 600px; background-color: rgb(0,0,255); }'; ?> </style> </head> <body onload="load()"> <div id="main"> <?php if (isset($_POST['submitted'])) { $bars = $_POST['stages']; $first = $_POST['first']; $last = $_POST['last']; echo "You entered $bars stage(s). "; echo "Your first color is $first. Your last color is $last."; //Gradient display code: // echo '<div id="leftbar"></div>'; } else { /* The two following tags MUST included in a form that YOU design within * this section of PHP code. */ // Function to create a uniquely named 20+ color select menu function Selectors ($a){ echo '<select name="$a">'; echo '<option value="127,255,212">Aquamarine</option>'; echo '<option value="0,0,0">Black</option>'; echo '<option value="0,0,255">Blue</option>'; echo '<option value="220,20,60">Crimson</option>'; echo '<option value="0,255,255">Cyan</option>'; echo '<option value="148,0,211">Dark Violet</option>'; echo '<option value="255,20,147">Deep Pink</option>'; echo '<option value="255,215,0">Gold</option>'; echo '<option value="255,0,255">Magenta</option>'; echo '<option value="25,25,112">Midnight Blue</option>'; echo '<option value="255,165,0">Orange</option>'; echo '<option value="128,0,128">Purple</option>'; echo '<option value="255,0,0">Red</option>'; echo '<option value="65,105,255">Royal Blue</option>'; echo '<option value="192,192,192">Silver</option>'; echo '<option value="135,206,235">Sky Blue</option>'; echo '<option value="0,255,127">Spring Green</option>'; echo '<option value="64,224,208">Turquoise</option>'; echo '<option value="238,130,238">Violet</option>'; echo '<option value="255,255,0">Yellow</option>'; echo '</select>'; } // Variables to use when calling the previous function $f = "first"; $l = "last"; //begin html form echo '<form action="tvtest.php" method="POST">'; //Hidden input... echo '<input type="hidden" name="windowWidth" id="windowWidth" />'; echo '<input type="hidden" name="windowHeight" id="windowHeight" />'; // Input table echo '<table>'; echo '<tr>'; echo '<td><label>First Color:</lable></td>'; echo '<td>'; Selectors($f); echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td><label>Second Color:</lable></td>'; echo '<td>'; Selectors($l); echo '</td>'; echo '</tr>'; echo '<tr>'; echo '<td><label>Number of Stages: </label></td>'; echo '<td><input type="text" name="stages" /></td>'; echo '</tr>'; echo '<tr>'; echo '<td colspan="2">'; echo '<input type="submit" name="submitted" value="Show Pattern" /></td>'; echo '</tr>'; echo '</table>'; echo '</form>'; //End html form } ?> </div> </body> </html> Hey I have a script that registers users, but i cannot work out why it will not process the information. I echo'd the variables and its all correct yet it just will not do it =/ This is the script i have - was hoping some one might be able to see the mistake: database script: Code: [Select] <?php class DB extends mysqli { public function execute($query) { echo $query; return $this->query($query); } public function qstr($str) { if (is_array($str)) { return $this->qstrArr($str); } return "'{$this->real_escape_string($str)}'"; } public function qstrArr($arr) { foreach ($arr as $key => $value) { $arr[$key] = $this->qstr($value); } return $arr; } ?> Register Process Code: [Select] <?php $pass = $db->qstr($_POST['pass']); $user = $db->qstr($_POST['user']); $email = $db->qstr($_POST['email']); $db->execute("INSERT INTO users (username,pass,email) VALUES ($user,$pass,$email);"); ?> On the database script i echo the query and it displays like this: Quote INSERT INTO users (username,pass,email) VALUES ('test','098f6bcd4621d373cade4e832627b4f6','test@test.com'); So why could it not be working =/ i get no error displaying by the way. Hi Guys I hope its ok to post here with some problems im having. This is my 1st time with trying to use php, and my 1st time attempting to create a website. Im using some extensions from Webassist, and although they can cut down the time it takes to code php. There also not as stated on there website, and you need too pretty much understand Php too get them working. And i have been banging my head against walls for 6mth in there forum, which only ever seem too send you too w3schools website. In my mind thats not support more being Fobbed Off! I came across this forum and seen there are people out there too help, and everyone here seems to enjoy helping unlike webassist. I have a few problems, my 1st is on the index page. When i run it i get this error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') WHERE id = -1 AND ((type = 'Dog')) AND ((country = 'England')) LIMIT 0, 10' at line 1 i will add the index page for anyone too look at, thanks in advance of any help with this. Please help...I'm going blind!!! I am trying to set up a simple feedback form on a website. The form is at www.hotelguestdirect.com if you need to see that. This is the error I get...Parse error: syntax error, unexpected ',' in /home/content/h/o/t/hotelguestdir/html/survey.php on line 160 Here is my code <?php // Field Mapping $sFirstName = $_POST["txtFirstName"]; $sLastName = $_POST["txtLastName"]; $sHomeCity = $_POST["txtHomeCity"]; $sHomeState = $_POST["selHomeState"]; $sCountry = $_POST["selCountry"]; $sHotel = $_POST["txtHotel"]; $sCity = $_POST["txtCity"]; $sState = $_POST["selState"]; $sStayLength = $_POST["selStayLength"]; $sHowHelpful = $_POST["txtHowHelpful"]; $sImprovements = $_POST["txtImprovements"]; if (($sHotel == "") || ($sCity == "") || ($sState == "") || ($sStayLength == "") || ($sFirstName == "")) { print('<span style="color:#333; font-size:14px;">Please complete the required fields <a style="color:#333" href="index.html" onClick="history.go(-1);">Click here to go back</a></span>'); } else { $sMailFrom = 'info@hotelguestdirect.com'; $sMailTo = 'graphics.hgd@gmail.com'; $sMailSubject = 'Guest Survey - Key Holder Brochures'; $sMailBody = '<p>Guest Response Survey</p> <b>Hotel: </b>' . $sName . '<br /> <b>City: </b>' . $sCity . '<br /> <b>State: </b>' . $sState . '<br /> <b>Lenth of Stay </b> ' . $sStayLength . '<br /> <b>How was the brochure helpful: </b>' . $sHowHelpful . '<br /> <b>Input or Improvements: </b>' . $sImprovements . '<br />'; $sMailHeaders = "From: $sMailFrom\n"; $sMailHeaders = "Content-Type: text/html; charset=iso-8859-1\r\n"; if (mail($sMailTo, $sMailSubject, $sMailBody, $sMailHeaders)) { print('<span style="color:#333; font-size:14px;"><div align="center"><br /><br />Thank you, your information has been emailed!</div></span>'); } else { print('<span style="color:#333; font-size:14px;"><div align="center"><br /><br />Could not send e-mail, please contact the webmaster!</div></span>'); } } ?> I beleive that my code is "ok" overall, but i am getting a syntax error on lines 6 & 26, pretty sure im making a stupid mistake here, Code is a plugin for a PHP IRC Bot, basically a toggle on/off command via "!radio" to send meta data from the audio stream every 5minutes. <?php require_once('shoutcast_class.php'); $radio = false; class plugRadio{ public static function onCommandRadio( if($radio == false) $radio = true; $dh->reply('3 Info Stream : ON', $event->getName(), $dh->getCommandTrailing()); while($radio == true){ event $event, datahelper $dh = null, $help = 'use !Radio to toggle stream info On/Off') { $display_array = array("Stream Title", "Stream Genre", "Stream URL", "Current Song", "Server Status", "Stream Status", "Listener Peak", "Average Listen Time", "Stream Title", "Content Type", "Stream Genre", "Stream URL", "Current Song"); $radio = new Radio("radio.anonops.ru:8000"); $data_array = $radio->getServerInfo($display_array); $dh->reply('15,1 #RadioPayback | 9,1On Air: '.$data_array[8].' 15,1| 9,1Now Playing: '.$data_array[12].' ', $event->getName(), $dh->getCommandTrailing()); $event->delete(); flush(); sleep(300); } } if($radio == true) $radio = false; $dh->reply('4 Info Stream : OFF', $event->getName(), $dh->getCommandTrailing()); } ?> My DB is holding time as "11:00 AM" "10:00 AM" ect... Is there a way to convert these to time() after I have queried the DB for results? <?php connect(); $query = "SELECT * FROM party WHERE year(DOP) = '2011' order by PTIMES asc"; $qt=mysql_query($query); echo mysql_error(); while($nt=mysql_fetch_array($qt)){ echo " <tr height='30'> <td id='label'>".$nt['NOC']."</td> <td id='labeloff'>".$nt['CFN']." ".$nt['CLN']."</td> <td id='labeloff'>".$nt['type']."</td> <td id='label'>".birthday($nt['DOB'])."</td> <td id='label'>$DOP</td> <td id='labeloff'>".$nt['PTIME']."</td> <td id='labeloff'>".$nt['act1']."</td> <td id='labeloff'>".$nt['act2']."</td> <td id='label'>".$nt['pizza']."</td> <td id='label'>".$nt['fc']."</td> </tr> "; }free($qt); ?> Thank you. ignore I wish to use the code from the following page that can be used to check if an uploaded image is an animated GIF: http://stackoverflow.com/questions/280658/can-i-detect-animated-gifs-using-php-and-gd Here is the function: function is_ani($filename) { if(!($fh = @fopen($filename, 'rb'))) return false; $count = 0; //an animated gif contains multiple "frames", with each frame having a //header made up of: // * a static 4-byte sequence (\x00\x21\xF9\x04) // * 4 variable bytes // * a static 2-byte sequence (\x00\x2C) // We read through the file til we reach the end of the file, or we've found // at least 2 frame headers while(!feof($fh) && $count < 2) $chunk = fread($fh, 1024 * 100); //read 100kb at a time $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00\x2C#s', $chunk, $matches); fclose($fh); return $count > 1; } Am I right in saying that there are curly brackets missing after the while line? The indenting indicates that both of the 2 following lines should be included in the while loop, but the lack of curly brackets mean that only the line beginning with $chunk is included in the loop. The code actually seems to work with and without the curly brackets. Does anyone understand this code well enough to know whether or not the curly brackets should be included? Thanks in advance. Hi Guys I'm trying to get clients to: 1. upload an image 2. fill out details 3. submit image and details to me via email 1. Uploading the image is fine, they choose it and it displays on the next page 2. They fill in form details 3. then click submit to send to me - I get all details except the image How do I keep the image variable around to insert it into the details form and email it? The image appears to be displayed on the second page, then the variable disappears (is deleted) and isn't available in step 3 to submit as part of the email. I'm sure it's a simple fix - I'm pretty new with php and I've started kicking things so I thought it was time to ask for help. Upload-image-code <?php if($_FILES) { $img = $_FILES['filename']['img']; switch($_FILES['filename']['type']) { case 'image/jpeg' : $ext = 'jpg'; break; case 'image/png' : $ext = 'png'; break; default: $ext = ''; break; } if ($ext) { $n = "image.$ext"; move_uploaded_file($_FILES['filename']['tmp_name'], $n); echo "<span class='uploaded-photo'>uploaded image '$img' as '$n':</span> <br />"; echo "<img src='$n' />"; } else echo "'$img' is not a supported image file"; } //else echo "<span class='uploaded-photo'>No image has been uploaded</span>"; ?> $n is available to be displayed on page 2 and it works Page 2 contains the rest of the form, but when I submit the form $n isn't available to be sent with the other data (i have tried REQUEST $img as well. Submit form code <?php $name = $_REQUEST['name'] ; $email = $_REQUEST['email'] ; $phone = $_REQUEST['phone'] ; $address = $_REQUEST['address'] ; $pname = $_REQUEST['pname'] ; $pdescription = $_REQUEST['pdescription']; $plow = $_REQUEST['plow'] ; $phigh = $_REQUEST['phigh'] ; $purl = $_REQUEST['purl'] ; $ponline = $_REQUEST['ponline'] ; $n = $_REQUEST['n']; $img = $_REQUEST['img']; if (!isset($_REQUEST['email'])) { echo "we need your name and email address please" ; } elseif (empty($name)){ echo "please enter your name"; } elseif (empty($email)){ echo "please enter your email address"; } elseif (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})", "$email")) { echo"please check your email address - it doesn't appear to be a valid format"; } else { mail( "eamail@address.com", "Subject", "$name\n $email\n $phone\n $address\n $pname\n $pdescription\n $plow\n $phigh\n $purl\n $ponline\n $n\n $img", "$email"); header( "Location: ../index.php" ); } ?> Would really appreciate any help - if you need full code please let me know. Thanks @webecho Still forgetting it. Code: [Select] <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); $data = array(); class Main extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper('form'); $this->load->helper('html'); $this->load->helper('url'); $this->load->library('ion_auth'); $this->load->library('session'); $this->load->library('form_validation'); $this->load->database(); //$this->load->model('prod_m'); } function login() { $this->$data['header'] = $this->load->view('header', null, TRUE); $this->load->view('front_page', $this->data); } } /* End of file main.php */ /* Location: ./application/controllers/main.php */ All I just is to make the $data array variable as public and works across all function inside the class. Where did I made wrong? Thanks in advance. I am doing something stupid, and just can't see it and hoping someone has better eyes than mine. I have two Doctrine entities which extend another class using single class inheritance, but when retrieving the collection of either of the two child classes, I get the collection of the parent (i.e. combination of both child classes). I've experimented with making the parent abstract and not including it in the discriminator map but no change. In hopes to identifying my mistake, I created a new Symfony project with just the relevant classes and show all steps below. Initial install by running the following: symfony new test composer update composer require doctrine/orm composer require migrations composer require maker --dev composer require security Using "php bin/console make:user", I created three users: AbstractUser, OwnerUser, VendorUser. I then edited all three entities and the owner and vendor repositories as follows: <?php namespace App\Entity; use App\Repository\AbstractUserRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Security\Core\User\UserInterface; /** * @ORM\Entity(repositoryClass=AbstractUserRepository::class) * @ORM\InheritanceType("SINGLE_TABLE") * @ORM\DiscriminatorColumn(name="discr", type="string") * @ORM\DiscriminatorMap({"owner" = "OwnerUser", "vendor" = "VendorUser", "abstract" = "AbstractUser"}) */ class AbstractUser implements UserInterface { // No changes made }
<?php namespace App\Entity; use App\Repository\OwnerUserRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=OwnerUserRepository::class) */ class OwnerUser extends AbstractUser { }
<?php namespace App\Entity; use App\Repository\VendorUserRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=VendorUserRepository::class) */ class VendorUser extends AbstractUser { } No change to AbstractUserRepository. <?php namespace App\Repository; class OwnerUserRepository extends AbstractUserRepository { }
<?php namespace App\Repository; class VendorUserRepository extends AbstractUserRepository { } Then I migrated the DB. php bin/console doctrine:schema:drop --full-database --force rm migrations/* php bin/console make:migration php bin/console doctrine:migrations:migrate Next I created two OwnerUsers and one VendorUser using a command script I wrote shown at the end of this post. # php bin/console app:tester create OwnerUser roles=[] # php bin/console app:tester create OwnerUser roles=[] # php bin/console app:tester create VendorUser roles=[] Checked the PostSQL database. facdocs=> \d List of relations Schema | Name | Type | Owner --------+-----------------------------+----------+--------- public | abstract_user | table | facdocs public | abstract_user_id_seq | sequence | facdocs public | doctrine_migration_versions | table | facdocs (3 rows) facdocs=> select * from abstract_user; id | email | roles | password | discr ----+-------------+-------+----------------+-------- 1 | setEmail158 | [] | setPassword146 | owner 2 | setEmail87 | [] | setPassword101 | owner 3 | setEmail62 | [] | setPassword20 | vendor (3 rows) facdocs=>
Next, I retrieved the entities using Doctrine along with the beforementioned test script. [michael@devserver test]$ php bin/console app:tester read VendorUser Test Entity Manager ============ command: read entity: VendorUser class: \App\Entity\VendorUser properties: [] array(3) { [0]=> object(stdClass)#293 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(1) ["email:App\Entity\AbstractUser:private"]=> string(11) "setEmail158" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword146" } [1]=> object(stdClass)#294 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(2) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail87" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword101" } [2]=> object(stdClass)#358 (5) { ["__CLASS__"]=> string(21) "App\Entity\VendorUser" ["id:App\Entity\AbstractUser:private"]=> int(3) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail62" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(13) "setPassword20" } } [michael@devserver test]$ [michael@devserver test]$ php bin/console app:tester read OwnerUser Test Entity Manager ============ command: read entity: OwnerUser class: \App\Entity\OwnerUser properties: [] array(3) { [0]=> object(stdClass)#293 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(1) ["email:App\Entity\AbstractUser:private"]=> string(11) "setEmail158" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword146" } [1]=> object(stdClass)#294 (5) { ["__CLASS__"]=> string(20) "App\Entity\OwnerUser" ["id:App\Entity\AbstractUser:private"]=> int(2) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail87" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(14) "setPassword101" } [2]=> object(stdClass)#358 (5) { ["__CLASS__"]=> string(21) "App\Entity\VendorUser" ["id:App\Entity\AbstractUser:private"]=> int(3) ["email:App\Entity\AbstractUser:private"]=> string(10) "setEmail62" ["roles:App\Entity\AbstractUser:private"]=> string(8) "Array(0)" ["password:App\Entity\AbstractUser:private"]=> string(13) "setPassword20" } } [michael@devserver test]$
As seen, when requesting a collection of either OwnerUsers or VendorUsers, I am retrieving the combination of both collections. I am sure it is totally user (i.e. me) error, but just don't see it. Are you able to see my stupid mistake? Thanks
<?php namespace App\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputArgument; use Doctrine\ORM\EntityManagerInterface; use Doctrine\Common\Util\Debug; class Tester extends Command { // the name of the command (the part after "bin/console") protected static $defaultName = 'app:tester'; private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; parent::__construct(); } protected function configure() { $this ->setDescription('Doctrine Object Tester. --help') ->setHelp('This command allows you to query a single entity...') ->addArgument('cmd', InputArgument::REQUIRED, 'The command name [create, read].') ->addArgument('entity', InputArgument::REQUIRED, 'The name of the entity.') ->addArgument('properties', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'properies (foo=foo bla=[]') ; } private function getProperties($input) { $properties=[]; foreach($input as $property) { $property=explode('=', $property); $name = trim($property[0]); $value = trim($property[1]); if($value === '[]') { $value = []; } elseif($value === 'null') { $value = null; } elseif(substr($value, 0, 1) === '/') { $value = explode('/', substr($value, 1)); $class = ucfirst(substr($value[0], 0, -1)); $class = '\App\Entity\\'.$class; if(count($value)===1) { $value = $this->entityManager->getRepository($class)->findAll(); } else { $value = $this->entityManager->getRepository($class)->find($value[1]); } } $properties[$name] = $value; } return $properties; } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln([ 'Test Entity Manager', '============', '', ]); // retrieve the argument value using getArgument() $cmd = $input->getArgument('cmd'); $output->writeln('command: '.$cmd); $entity = $input->getArgument('entity'); $output->writeln('entity: '.$entity); $class = '\App\Entity\\'.$entity; $output->writeln('class: '.$class); $properties = $this->getProperties($input->getArgument('properties')); $output->writeln('properties: '.json_encode($properties)); switch($cmd) { case 'create': $entity = new $class; foreach(get_class_methods($entity) as $method) { if(substr($method, 0, 3)==='set') { $m = lcfirst(substr($method, 3)); $entity->$method(array_key_exists($m, $properties)?$properties[$m]:$method.rand(0,200)); } } $this->entityManager->persist($entity); $this->entityManager->flush(); $output->writeln('entity created'); break; case 'read': Debug::dump($this->entityManager->getRepository($class)->findAll()); break; default: $output->writeln('INVALID COMMAND: '.$cmd.'. Only create and read are supported.'); } return Command::SUCCESS; } }
|