Jump to content

adding data from php page in mysql database


zed_fuma
Go to solution Solved by zed_fuma,

Recommended Posts

Hi! Can anyone help me with this?

I'm pretty much a newbie in php and mysql but I have a project to make for school so I need it.

As the topic title says I just simply want to add the data collected through the form on the insert.php page directly in the database.

I tried to change " with ' or other stuff but it doesn't work. I use xampp server by the way.

 

template.css

insert.php

Link to comment
Share on other sites

Hey man I'd be happy to help you, I've mostly been asking rather than giving here so here goes...

 

First you need a connection to the database, and the table name as well as the names of the columns

 

Let's say you've got a form that asks for a name, an age and a bio.

 

I would use four columns for this, the fourth being a unique idenfitication 

 

This is the code, save it as a .php file so the php part executes

 

I went through a lot here, you asked for separate eg. action="somewhere.php" but I think that is bad from what I have experienced although in retrospect a delete function uses action="delete.php" for example so... usually forms redirect to themselves for the error checking aspect, someone else may chime in.

 

This code was stripped from one of my functioning websites. Most of this code was given to me, this template from coding forums so I'm happy to help you out.

 

POST is when you hit "submit" so if you read through the code, when the page is first loaded, nothing happens, until a person fills in the form then hits submit, you see if something POST, then the code is executed, error checks are done, if no errors, data is inserted. I've also attached error logs above to displayed if there are any problems.

<?php
// the MYSQLI_REPORT_OFF is turned off because of a known problem with indexes 

mysqli_report(MYSQLI_REPORT_OFF);
error_reporting(E_ALL);
error_reporting(-1);

// your server-database connection here

$servername = "localhost";
$username = " "; // usually is root
$password = " ";
$dbname = " ";

$link = new mysqli("$servername", "$username", "$password", "$dbname");

if($_SERVER['REQUEST_METHOD']=='POST'){

// this is an array to hold errors such as entering a number in the name field
$errors = array();

// a sample error test

if (empty($_POST['name'])){
$errors['name'] = "a name is required";
}else {
$name = $_POST['name'];
}

if(empty($errors)){

$id = ""; left empty for database to fill in by auto_increment
$name = $_POST['name'];
$age = $_POST['age'];
$bio = $_POST['bio'];

// User is the name of your table
// the number of questions matches the number of columns you have in your table
// the question marks are for paramenter binding to prevent people from injecting bad code
// notice the 'isis' this has to match the data type of your columns, so in sequence, $id, $name, $age, $bio would be of data types int, varchar, int, text which varchar and text are both strings

$stmt = mysqli_prepare($link, "INSERT INTO User VALUES (?,?,?,?)");
$stmt->bind_param('isis',$id,$name,$age,$bio);

$stmt->execute();

// a message to be displayed upon the completion of the insert shown below in the html where it would appear

$_SESSION['status_message'] = "Data inserted";

// this refreshes the page after posting you can redirect to a new page here by chaging the $host and $uri to something like name.com/somewhere.html

$host  = $_SERVER['HTTP_HOST'];
        $uri   = $_SERVER['REQUEST_URI']; // the path/file?query string of the page
        header("Location: http://$host$uri");
        exit;
        $link->close();

}

}

?>

<!DOCTYPE HTML>
<head>
<style>
// can add a style here for the inputs or submit button
input[name="name"]{
width: 200px;
height: auto;
font-size: 100%;
color: black;
}
.errors {
color: red;
font-size: 100%;
}
</style>
</head>
<body>
<?php

// here is an example of a redirect where you can go somewhere once the insert has been completed. This is a manual method, usually it is automatic and would be bypassed by a redirect above

if(isset($_SESSION['status_message'])){
    echo '<font color="#ff8400">'.htmlspecialchars($_SESSION['status_message']).'</font>'.' '.' '.
    '<a href="http://www.somewhere.com" class="linkfix">Go to my profile</a>';
    unset($_SESSION['status_message']); // clear the message
    }
?>

// the placeholders place the name of the field inside the input (where you type) and I think this is cleaner but I have shown both ways

<form method="post" action="">
<input type="text" name="name" placeholder="name">
<br>
// display error above name or next to it
<span class="errors"><?php echo isset($errors['name'])? $errors['name']:""; ?></span>
<br>
<input type="number" name="age" placeholder="age">
<br>
name <input type="text" name="bio" placeholder="bio">
<br>
<input type="submit" name="submit" value="submit">
<br>
</form>
</body>



Edited by moose-en-a-gant
Link to comment
Share on other sites

what I need is mysql not mysqli or pdo. I need it for school and at school we make mysql and the teacher will know it's not mine if I use something like this. also I don't need all those error checks and other things yet, I'm keeping it simple for now, I'll take it one step at a time. I attached the files and I just want to know what I did wrong or what I need to correct and how.

Edited by zed_fuma
Link to comment
Share on other sites

Several things I see.

 

You do your DB inserts without first checking to see if the form submitted. So whenever you load the page it will be trying to insert things into the db, whether or not you filled anything out on the form.

 

The second thing is your genre checkboxes. Since they're checkboxes, many can be checked. You need to send those form values as an array, or only a single checkbox will be sent with your form (probably the last checked value). In order to submit it as an array, you'd need to add [] just after the NAME of that element.

<input type="checkbox" name="genre[]" value="Urban">Urban

 

After doing that, this will be an array:

$i=$_POST["genre"];

 

If you only want ONE genre to be selected, use radio buttons instead of checkboxes. Or another <select>.

 

How are you storing the genres in your db? That is not clear by the code you've provided. Can a movie have multiple genres?

Link to comment
Share on other sites

Also, you are kind of blind when running your queries. You don't check for an error and just assume it runs. How are you supposed to troubleshoot this if you don't see any errors?

 

I'd really change this line:

mysql_query($sql);

to this:

if ( ! mysql_query($sql))
{
  echo 'Invalid query: ' . mysql_error() . '<br><br>';
  die("Query: $sql);
}

so it will show you the exact problem MySQL is complaining about. You can always tell your teacher how smart you are and checked the PHP manual how to show errors like the first example on the mysql_query() page. :)

Link to comment
Share on other sites

what I need is mysql not mysqli or pdo. I need it for school and at school we make mysql and the teacher will know it's not mine if I use something like this. also I don't need all those error checks and other things yet, I'm keeping it simple for now, I'll take it one step at a time. I attached the files and I just want to know what I did wrong or what I need to correct and how.

 

mysqli is mysql "improved"

 

Anyway, no problem, good luck with your project

Link to comment
Share on other sites

someone helped me a bit and now it at least adds something in the database.

indeed I didn't make it clear, yes since I made checkboxes I want to put more genres to a movie. and yes you are right, it only shows the last one.

in the end the person who helped me also told me I should use mysqli and I changed the php part a bit to:

<?php
$a=mysqli_connect('localhost', 'root', 'root', 'movies') or die(mysqli_error($a));
if (!$a){
	echo mysqli_connect_errno().mysqli_connect_error();
}


$c=$_POST["Name"];
$d=$_POST["img"];
$e=$_POST["trailer"];
$f=$_POST["air"];
$g=$_POST["airdate"];
$h=$_POST["rate"];
$i=$_POST["genre"];
$j=$_POST["description"];
$sql="INSERT INTO movie(name,img,trailer,air,airdate,rate,genre,description)
VALUES('$c','$d','$e','$f','$g','$h','$i','$j')";
mysqli_query($a,$sql) or die(mysqli_error($a));
echo '';
?>

now I only have the problem with the genres, and the errors that distort the page. 

managed to do something about adding empty lines whenever I load the page with

if(isset($_POST['sub']))

where sub is the name for the submit button.

Edited by zed_fuma
Link to comment
Share on other sites

Can you make this more clear

 

now I only have the problem that it inserts data every time I load the page, the genres, and the errors that distort the page.

 

 

you need to trigger the insert by a button or POST not automatically like when you load the page.

Hence in the code I wrote in my first response there is an "IF.... POST" which is what checks when you reload the page if someone pressed submit.

 

The errors tha distort the page, what do you mean by that? Can you do a screen shot of your webpage? Or not, whatever helps you.

Link to comment
Share on other sites

Can you make this more clear

 

 

you need to trigger the insert by a button or POST not automatically like when you load the page.

Hence in the code I wrote in my first response there is an "IF.... POST" which is what checks when you reload the page if someone pressed submit.

 

The errors tha distort the page, what do you mean by that? Can you do a screen shot of your webpage? Or not, whatever helps you.

i edited the post, I managed to do the thing about the insert. by errors I mean these ones:1eDVVC2.png

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.