adding data to a database with PHP

Associate
Joined
6 Mar 2009
Posts
495
Im trying to add some data to a database and cant seem to get it to work. Here is what i have so far. Any suggestions or advice please??

//are we adding a new track to the 'selected tracks' list
if (isset($_GET["action"]) && $_GET["action"]=="addTrack") {
$trackID=$_GET["trackID"];

INSERT INTO selectedtracks VALUES(trackID);

$dbQuery ="select id, trackID from selectedtracks";
$dbResult=mysql_query($dbQuery);
echo mysql_num_rows($dbResult)."\n";}
 
You're mixing your PHP and SQL. This is PHP:

//are we adding a new track to the 'selected tracks' list
if (isset($_GET["action"]) && $_GET["action"]=="addTrack") {
$trackID=$_GET["trackID"];

$dbQuery ="blah";
$dbResult=mysql_query($dbQuery);
echo mysql_num_rows($dbResult)."\n";}

And this is SQL:

INSERT INTO selectedtracks VALUES(trackID);
select id, trackID from selectedtracks

Those two lines are seperate queries. One will insert data into the database, one will select data from a database for display. You don't want the second one.

What you want to do is execute the INSERT query:

//are we adding a new track to the 'selected tracks' list
if (isset($_GET["action"]) && $_GET["action"]=="addTrack") {
$trackID=$_GET["trackID"];

$dbQuery ="INSERT INTO selectedtracks VALUES(" . $trackID . ")";
$dbResult=mysql_query($dbQuery);
}

Also you can't do a num_rows after an INSERT; it won't return any data. If you want to return the dataset do a separate SELECT afterwards.

I'd recommend you do a little research on the difference between SQL and PHP, you can't just mix SQL with PHP code like that. You have to execute the SQL as a query.
 
Last edited:
Ok thanks. Got a little further now but getting another error. Error at this line - $dbResult=mysql_query($dbquery); saying that $dbResult is undefined!!

$dbQuery="insert into selectedtracks values (null , $trackID)";
$dbDisplayResult=mysql_query($dbQuery);

// now retrieve the artist name and song title for every entry in the
// selectedTracks table. Return the tracks/artists in an
// unordered list with a suitable heading e.g.

$dbQuery="SELECT tracks.title, artists.name
from tracks, artists, selectedtracks
where selectedtracks.trackid=tracks.id
and tracks.artistid=artists.id";

$dbResult=mysql_query($dbquery);
while ($dbRow=mysql_fetch_array($dbResult)) {
echo "<ul>".$dbRow["title"]."^".$dbRow["name"]."\n </ul>";
}
 
debugging:

Try doing

PHP:
print_r($dbResult);
after you 'populate' it.
Should look like this but with your data.

PHP:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
if it doesn't show results, then your issue is that it's not querying the database properly.

And are you sure you have information in the db?
 
Last edited:
Back
Top Bottom