B. Krafft
B. Krafft

Reputation: 167

Syntax to create a dynamic string in PHP

I am going cross-eyed trying to figure out my syntax error here.

I have a table that I create dynamically. The user can click on one cell in a row to get an alert with notes in it.

The problem is that my quote marks are incorrect no matter what I do. I'm obviously not seeing something.

This PHP code

"<td onclick='showNotes()' ></td>";

Gets me in my HTML code upon rendering

<td onclick="showNotes()"></td>

This looks good and executes my jQuery no problem. So far so good.

========================================================

This PHP code (where $col contains the notes to be displayed)

"<td onclick='showNotes(" . $col . ")' ></td>";

gets me this in my HTML

<td onclick="showNotes(myNewNotes)"></td>

The only problem here is that myNewNotes is a string and needs to have quotes around it, or else I get an error that it is not defined. OK, moving along.

========================================================

So now I try this PHP code

"<td onclick='showNotes(" . "'" . $col . "'" . "')' ></td>";

Which gets me this in the HTML, which is crap.

<td onclick="showNotes(" myNewNotes'')'></td>

=========================================================

WHAT is going on?

Upvotes: 1

Views: 397

Answers (3)

happymacarts
happymacarts

Reputation: 2595

How about this

    echo "td onclick='showNotes(" .'"'. $col .'"'. ")' ></td>";

Upvotes: 0

aynber
aynber

Reputation: 23011

You can escape quotes within your string, which will get you what you need:

"<td onclick='showNotes(\"$col\")' ></td>";

Upvotes: 4

ScaisEdge
ScaisEdge

Reputation: 133370

Normally you should use escape \ this way

  "<td onclick='showNotes(\'" .  $col ."\');' ></td>";

Upvotes: 0

Related Questions