How do I insert a related row into a mysql database? - php

I'm completely stumped. I have two tables set up in my database, one called subjects and one called pages. I gave the pages a subject_id in my database to connect them to subjects. I've dynamically displayed a nav containing the subjects and there child pages. I've also created a few php files that delete subjects, edit subjects, and edit pages. I've now added a link onto each subject so that when you click on the subject, it takes you to a page where, hopefully, I'll be able to add a new page under the chosen parent subject. It's also worth noting that i am sending the parent subject id in the link to add the page.
Here's the fraction of code that i believe is somehow giving me problems:
if(empty($errors)){
$id = mysql_prep($_GET['subj']);
$menu_name = mysql_prep($_POST['menu_name']);
$position = mysql_prep($_POST['position']);
$visible = mysql_prep($_POST['visible']);
$content = mysql_prep($_POST['content']);
$subject = get_subject_by_id($id));//This fetches the subject id from the db
$query = "INSERT INTO
pages WHERE subject_id = $subject
(
menu_name, position, visible, content
) VALUES (
'{$menu_name}', {$position}, {$visible}, '{$content}'
)";
$result = mysql_query($query, $db_connect);
if (mysql_affected_rows() == 1){
echo "<p>suceess</p>";
} else { ....
I know this is out of context but i thought someone might have some luck by spotting the problem. If anybody has ANY insight on this I would appreciate it.

You can't have a where clause in an insert statement.
Without the where clause the table will get the inserted row. If you are trying to update an existing row, which would justify a where clause, then you need to use an update statement.

the correct INSERT syntax is:
INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES (?,?,?,?,?)
of course, bind with the appropriate parameters and do not use string interpolation.

Related

How to update database values for a whole day

I am building a web application, for travelling. I have managed to get users to be able to insert how much they have spent on each category (i.e. travel, accomodation, food, etc) into the database once from a form. However, I want them to be able to contiously add to the total value of each category for just that day using the same form, and then everyday have a new total for each category as well.
I'm not quite sure how I would do that at the moment.
Here is my code so far for inserting the values into the database from my form (which works):
if(isset($_POST['addinfo_button'])){
$Food = $_POST['food'];
$Transport = $_POST['transport'];
$Accom = $_POST['accomodation'];
$Entertain = $_POST['entertainment'];
$Souvenir = $_POST['souvenirs'];
$Misc = $_POST['miscellaneous'];
$Date = date("Y-m-d");
$Trip_id;
$sql = "SELECT * FROM trips WHERE id =$user_id_session AND date1 <= '$Date' && date2 >= '$Date'";
$records = mysql_query($sql);
while($trip=mysql_fetch_assoc($records)){
$Trip_id = $trip['trip_id'];
}
$foreignkey = $user_info['id'];
$sql = $con->query("INSERT INTO todays_spend (food, transport, accomodation, entertainment, souvenirs, miscellaneous,date, trip_id, id)Values('{$Food}', '{$Transport}', '{$Accom}', '{$Entertain}','{$Souvenir}', '{$Misc}','{$Date}','{$Trip_id}','{$foreignkey}')");
header('Location: budgetbuddy.php');
}
Would I have to do something similar to this? or modify this one slightly?
Could not write code for you. But I can give you an Idea how you can achieve this having only one form.
Create a table with your needs.I mean your entertainement, food, etc along with their name and Id. If you can make user enter their name or anything that users can uniquely identified. Then things go easier. When a user enter their how much they spent insert into table along with their name or identifier. Next time same user enter details simply find if already user has anything updated on same day , if user added anything before simply update the table by adding previously existing values to new values. Update them. Now you easily even find how much each user spent on particuler catogery.Hope it helps. Thank you.

Updating array values for a particular id in database

Im working on a web application where i need to let users update several tds in a tr of a table. As of now i can fetch and show the database values in the respective td's. But when i try to update them, the last entered values in the last tr gets updated for all the td's in the table.
Below is the part of the query im trying. All the values are considered array since values are gathered from several input box.
$cno="123";
$c = count($ndv);
for($i=0;$i<$c;$i++)
{
$query_dv="UPDATE device SET cid = '$cno',name = '$ndv[$i]',type = '$tdv[$i]',serialno = '$sdv[$i]',model = '$mdv[$i]',location = '$ldv[$i]' WHERE cid = ".$cno;
$sql_device = mysqli_query($conn, $query_dv) or die(mysqli_error($conn));
}
so say right now i try to update with values 123,1,1,1,1,1 and 123,2,2,2,2,2
i get 123,2,2,2,2,2 and 123,2,2,2,2,2 .. i do understand that its getting reupdated due to the for loop. So im trying to fix this part of the code. And im struggling to fix it. Any help would be appreciated.
Your issue is you are not uniquely identifying the row you are wanting to update, todo this add a column to your database called something like id make it the primary key and have it auto increment, then in your table add a hidden/disabled input containing the id and update your query to be something along the lines of
$query_dv="UPDATE device SET name = '$ndv[$i]',type = '$tdv[$i]',serialno = '$sdv[$i]',model = '$mdv[$i]',location = '$ldv[$i]' WHERE id = " . $id[$i];
I removed the update for cid because from your question it doesn't look like it changes so no need to update.

Getting Auto Increment multiple times

I'm hoping someone can help me figure out what I thought would be really easy.
I have a form that I dynamically add rows to. When I add the row, I want to display a unique value, and am using the MySql table primary key - called ID. Because there will be multiple users, I want to immediately reserve that ID, so it doesn't get reused. Since a user may decide to add another item to the list, and add another dynamic row, I want to repeat the process (get the new Auto Increment value from that table, and immediately reserve it).
Unfortunately, I continue to get the same ID value, even though I have confirmed the auto increment value has increased.
This is what I am using inside my "add row" function before I use the DOM Element to add the row:
$result = mysql_query("SHOW TABLE STATUS LIKE 'table'");
$row = mysql_fetch_array($result);
$nextId = $row['Auto_increment'];
$query = "INSERT INTO table (id, identifier1, identifier2) VALUES ('".$nextId."','".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
I have tried adding immediately before them the following in the hopes that it will blank everything and pull all new values:
$nextId = 0;
$row = "";
$result = "";
$query = "";
I am hoping someone out there can see something simple or suggest a better way that will work.
Thanks in advance.
Ok as your comment shows you have a slight mistake in your INSERT, try this:
$query = "INSERT INTO table (identifier1, identifier2)
VALUES ('".$identifier1."','".$identifier2."')";
$result = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id()+1; //you also need to +1 to get the next number
But there is NO guarentee that the next id will be +1 from the last.

Retrieve and display comments/queries from database

I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)

variable values conflicts with multiple user

Iam new to PHP, trying to do personalized search engine it works fine with the single user... but simultaneously 2 user uses.. the values in the Variable showing wrong values.
Eg:
if user1 search "Apple" then $qry="Apple", same time user2 search "orange" then $qry="orange" that time the user1 will get the remaining stuffs related "orange".
function storewords($str,$id)
{
$words= str_word_count($str,1);
$cntstr = count($words);
//echo $cntstr;
for($i=0;$i<$cntstr;$i++)
{
$allwords= $words[$i];
$insert = "INSERT INTO freq (word,extra) VALUES ('".$allwords."','".$id."')";
$add_member = mysql_query($insert);
}
}
Which i have process of preprocessing, extracting concept for each user's content.. each user have different content.
I think i have expressed my doubt in correct word, if no please excuse. Please help me, Thanks in advance
You just have to store user id somehow, to get separate "searches" for each user later.
$insert = "INSERT INTO freq (userid,word,extra) VALUES (...)";
Then you should select from that table using SELECT with filter like this: "WHERE userid=$current_user_id"

Categories