skip to Main Content

New to PHP, doing academical exercise. I have a website that lets you add cars from add-car.php. Car is an object with make, model, grade from Post.php. Add-car.php creates an entry and displays it on index.php with make, model and year.

I need to make the car entry ‘make’ into a hyperlink that lets me edit the original entry by taking me back to add-car.php with the values (make, model, year) already inserted into the form.

I have already implemented etc. into the original form, so that if there is an error (eg. model text is too long or too short) it keeps the previous value.

What I have trouble with is creating the correct hyperlink with values when the car entry is created. Right now I have in Post.php:

public function __toString(): string {

$url = printf('<a href=car-add.php?id=' . $this->id);

return printf('<div>"$url"</div><div>%s</div><div></div><div>%s</div>', $this->make, $this->model);

Output is:

<a href=book-add.php?id=12<div>26</div><div>BMW</div><div></div><div>5</div>54
<a href=book-add.php?id=13<div>26</div><div>Mercedes</div><div></div><div>5</div>54

No idea where the nr 26 and 54 are coming from.
Output should look like this:

<div><a href=book-add.php?id=12></a></div><div>BMW</div><div></div><div>I5</div>

<div><a href=book-add.php?id=13</a></div><div>Mercedes</div><div></div><div>Vito</div>54

I’m expecting that the hyperlink from index.php takes me back to add-car.php with the values of the Car object already inserted into the text fields.

Edit: Each car also gets an ID when a post is created, but I’m unsure how to implement the id. Car ID is in a separate txt.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you, @Markus Zeller. Got it formatted and working. Way better answer than my teacher gave. He basically said that I made too many mistakes to answer online.

    $url = '<a href=car-add.php?title=' . $this->title . '>';
    
    return sprintf('<div>' . $url . '%s</a></div><div></div><div>%s</div>', $this->title, $this->grade); 
    

  2. You need to use sprintf() to get the url into $url. If you use printf(), $url will always be a number, because printf() returns the string length created. That’s why you see the extra numbers.

    $url = sprintf('<a href=car-add.php?id=' . $this->id);
    

    Same is valid for your return statement.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search