I'm stuck on a posting script, I want information from mysql table 'category' from name to put that in mysql table 'post' to cat.
I cant get the data from category table in my html form "$row['name']
So when I click on sumbit the name from table 'category' example category called by 'name' test will be inserted into $cat
<html>
<body>
<title>ADD NEW POST</title>
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_post['cat'];
// insert data to mysql
$sql="INSERT INTO post(id, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if($result){
echo "Added a new post";
}
else {
echo "SOMETHING WENT WRONG!";
}
// end of post script ^^
?>
<?php
$query2 = mysql_query("SELECT * FROM `category` ");
while($row=mysql_fetch_array($query2)){
}
// html form start ?>
<form action="<?php $_PHP_SELF ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Picture link: <input name="pic" type="text" SIZE="80" id="pic"><br />
Youtube link: <input name="youtube" type="text" SIZE="80" id="youtube"><br />
Category game: <select name="name">
<option VALUE="<?php echo ''.$row['name'].''; ?>"><?php echo ''.$row['name'].''; ?></option>
<br /><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
You are vulnerable to SQL injection attacks. And if you have even bare bones minimal error handling in your code, you'd have been told WHERE the error is:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^-- you **NEED** this
As for the actual problem:
$sql="
INSERT INTO post(id, pic, youtube, cat)
^^^^^^^^^^^^^^^^^^^^^--- FOUR fields
VALUES
('$id', '$title', '$pic', '$youtube', '$cat')";
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- FIVE values
You're missing title in the field list.
Never EVER assume success. Assume everything will fail, code accordingly, and treat success as a pleasant surprise.
Related
I'm new to PHP Programming and MySQL. Regarding my question, I have 3 checkboxes. I need to select the data and save it to the database. if I choose 2 data, thus need to save the data 1 by 1, which means will insert two row of data. Below is my code example:
index.php
<!DOCTYPE html>
<html>
<body>
<h1>Show Checkboxes</h1>
<form action="save.php" method="POST">
<input type="checkbox" name="club[]" value="Chelsea">
<label for="Chelsea"> Chelsea</label><br>
<input type="checkbox" name="club[]" value="Liverpool">
<label for="Liverpool"> Liverpool</label><br>
<input type="checkbox" name="club[]" value="Arsenal">
<label for="Arsenal"> Arsenal</label><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
save.php
<?php
include("connect.php");
$club = implode(',',$_POST['club']);
$query = "INSERT INTO bpl_club (club_name) VALUES ('$club')";
$sql = $conn->prepare($query);
$sql->execute();
if($sql){
echo "<script>alert('Record inserted successfully!')</script>";
echo "<script>window.location = 'index.php'</script>";
}else{
echo "<script>alert('Something went wrong. Please try again!')</script>";
}
?>
Can anyone know how to fix it? Thank you so much..
Use foreach function to print your check box one one by from $_POST['club'] array
$ClubArray=array();
$ClubArray=$_POST['club'];
foreach($ClubArray as $ClubName)
{
//your Insert code here with the insert query ie INSERT INTO bpl_club (club_name) VALUES ('$ClubName')
}
I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.
select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.
I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.
Here is my code:
<div class="body_content">
<?php
$sid = null;
if(isset($_GET["subject"])) {
$sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name: <input type="text" name="menu" /> <br>
Position: <select name="position">
<?php
$new_page_query = select_all_pages_by_subject($sid);
$page_count = mysqli_num_rows($new_page_query);
for($count=1; $count<=($page_count + 1); $count++) {
echo "<option value=\"$count\">$count</option>";
}
?>
</select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
Cancel <br>
</form>
<?php
if(isset($_POST['submit'])) {
$menu_name = $_POST["menu"];
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = $_POST["content"];
$subject_id = (int) $_POST["$sid"];
$insert_query = "INSERT INTO pages (subject_id, menu_name, position,
visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
{$visible}, '{content}')";
$page_insert = mysqli_query($connection, $insert_query);
if($page_insert) {
$_SESSION["message"] = "Page created successfully";
redirect_to("admin.php");
} else {
$_SESSION["message"] = "Page creation failed";
redirect_to("create_page.php?subject=$sid");
}
}
?>
</div>
Edit: removed the WHERE statement
The problem is INSERT cannot have a WHERE after it.
$insert_query = "INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES ({$subject_id},'{$menu_name}', {$position}, {$visible}, '{content}')";
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:
<form action="create_page.php" method="post">
should be:
<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)
I need advice, what i did wrong and this code not working. In short I have droplist menu with data read from mysql database and I want this data what user selected put in to another table/row in db. with present code I received only NULL value in inserted row... some I assume maybe something wrong with syntax, I tried search similar topic and tried different way but result is same :| This is my code :
get function and form
<br><br>
<?php
include 'connectdb.php';
$sql="select * from persons";
$result=mysqli_query($con,$sql);
while ($row=mysqli_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$name_done.="<OPTION VALUE=\"$id\">".$name;
}
?>
<form action="insert.php" method="post">
<SELECT name="name_done" id="nane_done">
<OPTION VALUE=0>Choose Your name :
<?=$name_done?>
</SELECT> <br>
RFC: <input type="text" name="number"><br>
Date: <input type="text" id="datepicker" name="date">
<input type="submit" value="submit" />
</form>
And Insert
<?php
include 'connectdb.php';
$name_done = $_POST['nane_done'];
mysqli_query($con,"INSERT INTO rfc(name_done) VALUES (.$name_done)");
---- below working OK----
$sql = "INSERT INTO rfc(number,date)
VALUES
('$_POST[number]','$_POST[date]')";
if (!mysqli_query($con,$sql,$name_done))
{
die('Error: ' . mysqli_error($con));
}
echo "RFC added";
mysqli_close($con);
?>
You have a typo - "nane_done" rather than "name_done" in this line: $name_done = $_POST['nane_done'];.
Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.
having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message