• 0

Variables in MySQL Command


Question

I know you can have VALUES in MySQL query's be variables, but is there any way to set a table as a variable?

I have the following code...

$cat = $_POST['cat'];
$date = $_POST['date'];
$title = $_POST['title'];
$joke = $_POST['joke'];

$insert = "INSERT INTO $cat (id, date, title, joke) VALUES ('','$date','$title','$joke')"; 
mysql_query($insert) or die ("Could not add data to the table");

If I change $cat to a table name, it works. Is there any way to have the query recognize the $cat tho?

Link to comment
https://www.neowin.net/forum/topic/116067-variables-in-mysql-command/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

Theres no reason at all that shouldn't work, assuming $cat is actually getting the correct table name. all the mysql query is is a string passed to the database, so $insert is just a normal string variable - the mysql server has no idea it's any different. You could try backquoting (`) the table name, as this is allowed syntax for when the table name has spaces etc, but that could give you problems with spaces at the beginning / end of the POST'ed data

You may want to die(mysql_error()) to find out what the exact error is - that would be a *lot* more useful, as I can't see anything wrong with that code.

Are you sure $cat is getting initialised properly ? (eg stick a print statement just after the assignment).

The reason the others are in quotes is because thats SQL syntax - strings to be inserted have to be quoted, or it will take them as an sql keyword, and either generate errors, or not do what you want.

Hope this helped.

Also, on a purely good practice point, I'd question your inclusion of ID in the field list, as it is getting assigned '' each time. I'm assuming this is an autoincrement, for which I believe the correct method is to assign 0, or more preferably not assing anything at all. (What I'm saying is leave it out the fields and values list). If its not an autoincrement, its an empty string field, for which you could set that as a default value and leave it out anyway.

  • 0

Hmm, looks like you have an improperly normallized database. That means it's tables are not laid out correctly. You have a table for each category, but that's a problem. Try this format:

Table: categories

Fields: cat_id, cat_name

Table: jokes

Fields: joke_id, cat_id, date, title, joke

You fill the categories table with your available categories (plus, you can more easily create categories this way). Then you just link each joke their category and you can select them like this:

SELECT * FROM jokes j LEFT JOIN categories c ON c.cat_id = j.cat_id

That will give the jokes with their category names added on. You can also just change your form to SELECT * FROM categories and print ou the list of categories in a <select>. Then on the other end, you just grab the category id from the <select> and use it to insert the joke.

  • 0

If I'm correct, your query statement should look like this:

$insert = "INSERT INTO ".$cat." (id, date, title, joke) VALUES ('','".$date."','".$title."','".$joke."')";

Also, make sure that the tablename that you $_POST has the correct combination of upper and lowercase characters...

Greetings,

Thekk

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I thought router has to have 6 Ghz band to be called wifi-7, guess I was wrong...
    • I have the Pixel 9 Pro XL...Unless this thing is "leaps and bounds" faster than the 9, I'll pass. And by leaps and bounds, I don't mean on benchmarks. "Real world" faster. Most people don't even come close to topping out the performance of their phones. Tensor G5 is Google's most powerful chip to date, boasting a staggering 36 percent performance leap over G4.
    • MIT's stunning 'bubble wrap' device squeezes water out from thin air even in deserts by Sayan Sen Image by Matteo Roman via Pexels Massachusetts Institute of Technology (MIT) engineers have built a new kind of device that can pull clean drinking water straight out of the air—no electricity needed. It’s designed for areas where water is scarce and traditional sources like rivers or lakes aren’t reliable. Right now, more than 2.2 billion people globally don’t have access to safe drinking water. In the United States alone, 46 million face water insecurity, with either no running water or water that’s not safe to drink. This new device, called an Atmospheric Water Harvesting Window (AWHW), uses a unique hydrogel panel that looks like black bubble wrap. These dome-shaped bubbles soak up water vapor from the air, especially at night when humidity is higher. During the day, sunlight makes the vapor inside evaporate. That vapor then condenses on a glass surface and drips down through a tube, turning into drinkable water. The AWHW doesn’t rely on power sources like batteries or solar panels. It’s completely passive, meaning it works on its own. The team tested a meter-sized panel in Death Valley, California, one of the driest places in North America, and got between 57.0 and 161.5 milliliters of water per day even with humidity as low as 21 percent. That’s more than what other similar passive devices have managed. “We have built a meter-scale device that we hope to deploy in resource-limited regions, where even a solar cell is not very accessible,” said Xuanhe Zhao, a professor at MIT. “It’s a test of feasibility in scaling up this water harvesting technology. Now people can build it even larger, or make it into parallel panels, to supply drinking water to people and achieve real impact.” Another cool part of the design is how they kept the water safe to drink. Usually, these kinds of hydrogels use salts like lithium chloride to absorb more vapor but that can lead to salt leaking into the water, which isn’t ideal. To solve this, MIT’s team mixed in glycerol, a compound that helps keep salt locked inside the gel. In testing, the lithium ion concentration in the harvested water stayed below 0.06 ppm (parts per million), which is way below the safe limit. The hydrogel domes also give the material more surface area, letting it collect more vapor. The outer glass panel is coated with a special polymer film that helps cool the glass, making it easier for vapor to condense. “This is just a proof-of-concept design, and there are a lot of things we can optimize,” said lead author Chang Liu, now a professor at the National University of Singapore. “For instance, we could have a multipanel design. And we’re working on a next generation of the material to further improve its intrinsic properties.” Published in Nature Water, the study says the AWHW could last at least a year and shows promise for making safe, sustainable water in places with harsh climates. The researchers believe an array of vertical panels could one day supply water to individual households, especially in remote or off-grid locations. Source: MIT News, Nature This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • Clear Linux is open source, indeed, so its source code is available for anyone. They're just shutting down its support from them, they're not forbidding anyone else from taking over.
    • Linux Mint is also my favorite distro, but I fear what will happen with it if Clem were to disappear tomorrow, to be honest.
  • Recent Achievements

    • First Post
      leoniDAM earned a badge
      First Post
    • Reacting Well
      Ian_ earned a badge
      Reacting Well
    • One Month Later
      Ian_ earned a badge
      One Month Later
    • Dedicated
      MacDaddyAz earned a badge
      Dedicated
    • Explorer
      cekicen went up a rank
      Explorer
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      ATLien_0
      209
    3. 3
      Michael Scrip
      202
    4. 4
      Xenon
      144
    5. 5
      +FloatingFatMan
      121
  • Tell a friend

    Love Neowin? Tell a friend!