This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP / MYSQL Add button to column
Please correct any mistakes throughout this question - I am very new to both PHP and MYSQL.
My goal is to create a table, that I will display onto a web page that looks something like this:
I have done the following. Any help on where I go wrong is much appreciated.
Created a MYSQL Table named "CustomerInformation"
Added five columns to the table, identical to the five columns in the picture above; (id, name, email, is_admin, Action).
I made four $POST text boxes whose data will be passed into each column (other than the last one as I want an "action" button to appear there).
Below I will show my full code for which I used in order to populate a new row in my CustomerInformation table.
<?php
// Connect to the database
mysql_connect ("localhost","username","password") or die ('Error: ' . mysql_error());
echo "connected to database!";
mysql_select_db ("database");
// Create variables to retrieve the POST data
$ID= $_POST['textbox1'];
$C_ID= $_POST['textbox2'];
$Value= $_POST['textbox3'];
$Count= $_POST['textbox4'];
$action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
// Insert data into table
$query = "INSERT INTO CustomerInformation (ID,C_ID,Value,Count,Action)
VALUES(
'".$ID."', '".$C_ID."', '".$Value."', '".$Count."','".$action."')";
mysql_query($query) or die ('Error updating database');
echo "Database updated successfully!";
?>
The only problem occurs when I include the line: $action = ' "<input type="submit" name="AddRow" value="Add New Row" />"';
I am clearly butchering this line, and I would greatly appreciate any help at all on this one!
The answer to your question is quite simply mysql_real_escape_string. Apply it on each string variable before you intermingle it with the SQL command.
It's simpler however not to bother with the old mysql_ API. You can keep the query separate from the data and avoid the effort with:
$db = new PDO('mysql:host=hostname;dbname=db', 'username', 'pwd');
$db->prepare(" INSERT INTO CustomerInformation
(ID,C_ID,Value,Count,Action) VALUES (?,?,?,?,?) ")
->execute(array($ID, $C_ID, $Value, $Count, $action));
Related
I am not sure what I am doing wrong, can anybody tell me?
I have one variable - $tally5 - that I want to insert into database jdixon_WC14 table called PREDICTIONS - the field is called TOTAL_POINTS (int 11 with 0 as the default)
Here is the code I am using. I have made sure that the variable $tally5 is being calculated correctly, but the database won't update. I got the following from an online tutorial after trying one that used mysqli, but that left me a scary error I didn't understand at all :)
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
$sql = "INSERT INTO PREDICTIONS ".
"(TOTAL_POINTS) ".
"VALUES('$points', NOW())";
mysql_select_db('jdixon_WC14');
I amended it to suit my variable name, but I am sure I have really botched this up!
help! :)
I think you just need to learn more about PHP and its relation with MYSQL. I will share a simple example of insertion into a mysql database.
<?php
$con=mysqli_connect("localhost","peter","abc123","my_db");
// Check for errors in connection to database.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO Persons (FirstName, LastName, Age) VALUES ('Peter', 'Griffin',35)";
mysqli_query($con, $query);
mysqli_close($con); //Close connection
?>
First, you need to connect to the database with the mysqli_connect function. Then you can do the query and close the connection
Briefly,
For every PHP function you use, look it up here first.
(You will learn that it is better to go with mysqli).
http://www.php.net/manual/en/ <---use the search feature
Try working on the SQL statement first. If you have the INSERT process down, proceed.
You need to use mysql_connect() before using mysql_select_db()
Once you have a connection and have selected a database, now you my run a query
with mysql_query()
When you get more advanced, you'll learn how to integrate error checking and response into the connection, database selection, and query routines. Convert to mysqli or other solutions that are not going to be deprecated soon (it is all in the PHP manual). Good luck!
if(! get_magic_quotes_gpc() )
{
$points = addslashes ($tally5);
}
else
{
$points = $tally5;
}
mysql_select_db('jdixon_WC14');
$sql = "INSERT INTO PREDICTIONS (TOTAL_POINTS,DATE) ". //write your date field name instead "DATE"
"VALUES('$points', NOW())";
mysql_query($sql);
I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to code an order process. I have 3 different tables (orders, product, users) in a single database (dbphesemaas).
What I've tried so far doesn't work:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
mysql_close();
?>
Can someone make this code work, the id is a foreign key from users, while the product_id is a foreign key of product?
1. Error handling
You just connect and execute the query.
Well yeah nope - how are you making sure that everything worked?
Let's start off with error handling.
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbphesemaas');
?>
Is the connection working? Did the database get selected successfully?
You can use the if module to check if it worked.
<?php
// IF $link = mysql_connect('localhost', 'root', '') did not work (note the ! in front of it)
if(!$link = mysql_connect('localhost', 'root', '')){
die('Could not connect to localhost'); // The message displayed. die() will prevent the rest of the script from executing.
}
// IF database "dbphesemaas" did not get selected succesfully (note the ! in front of it)
if(!mysql_select_db('dbphesemaas', $link)){
die('Could not select the database "dbphesemaas"'); // The message displayed. die() will prevent the rest of the script from executing.
}
?>
Now we have the connection working. If something goes wrong, the script will stop being executed and throw a custom error.
2. Unnecessary variables
$username=$_POST["username"];
$area=$_POST["area"];
$product=$_POST["product"];
$address=$_POST["address"];
$dol_quantity=$_POST["quantity"];
Now is my question, why? There is nothing wrong with just using them inside the query. The only reason why you only would make variables is if the old variable is very long (so the chance of typo's are bigger) and/or if the code is too messy in your opinion. Since there is no problem in this code to use the $_POST variable, we're going to scratch this piece of code.
3. The actual query
$query="INSERT INTO orders (id, product_id, address, quantity) VALUES ('$id', '$id2', '$address', '$dol_quantity')";
There are a few problems here:
You wrote the query, but you aren't executing it.
You are using variables ($id, $id2 etc) inside quotes. In the wrong scenario, it's gonna insert $id in the database instead of the actual value.
Once again, no error handling.
No untainting at all. The user can add on into your query and alter the query, making a possible leak and the chance of being hacked bigger. We're going to prevent this with mysql_real_escape_string: http://php.net/manual/en/function.mysql-real-escape-string.php
Looks kinda messy, but that's just a visual problem.
Let's fix these problems:
$query="
INSERT INTO
orders
(
id,
product_id,
address,
quantity
)
VALUES
(
'". mysql_real_escape_string($_POST['id']) ."',
'". mysql_real_escape_string($_POST['id2']) ."',
'". mysql_real_escape_string($_POST['adress']) ."',
'". mysql_real_escape_string($_POST['quantity']) ."'
)
";
if(mysql_query($query)){
echo 'Succesfully executed the query.';
}
else
{
echo 'Query not executed - MySQL error. <br>';
echo '<pre>'. mysql_error() .'</pre>';
}
Using '". (random php code) ."' allows php code to be executed within a string. For example:
$variable = 'This is text '. strtoupper('this is capitalized since strtoupper makes this capital. note that this is inside the string.') .' and this is once again lowercase.';
4. Keep this for the future
The way I wrote these codes are useful for the future. Keep the use tabs every time you open/add a new bracket ({).
Further info - the default mysql_* functions are going to be deprecated as of PHP 5.5 - Use MySQLi in the future, it's the improved version. Info: http://www.php.net/manual/en/book.mysqli.php
5. For your actual problem
One mysql_query can only execute one query. You can do this:
$queries = array();
$errors = array();
$queries[] = 'INSERT INTO ... '; // using $variable[] will add another entry to the $variable array.
$queries[] = 'INSERT INTO ... ';
$queries[] = 'UPDATE bla SET ...';
foreach($queries as $query){
// Foreach will seperate the entries in an array
// IF mysql query failed
if(!mysql_query($query)){
$errors[] = mysql_error(); // We'll add the errors to an array aswell.
}
}
// Check if there are entries in the $failures array.
if(count($errors) > 0){
echo 'We had some MySQL errors.';
echo '<ul>';
foreach($errors as $failure){
echo '<li>'. $failure .'</li>';
}
echo '</ul>';
}
else
{
echo 'No errors - MySQL queries executed succesfully.';
}
Hope this helps you on your way.
I've been getting better at PHP - but I have NO idea what I'm doing when it comes to MySQL.
I have a code
<IMG>
I need to grab the "for", "affi" and "reff" and input them into a database
//Start the DB Call
$mysqli = mysqli_init();
//Log in to the DB
if (!$mysqli) {
die('mysqli_init failed');
}
if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!$mysqli->real_connect('localhost', 'USERNAME', 'PASSWORD', 'DATABASE')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
That's what I'm using to create a connection. It works. I've also got a table created, call it "table", with rows for "for", "affi", and "reff".
So my question is... someone gets directed to http://www.example.com/test.php?for=abcde&affi=12345&reff=foo
Now that I've got a DB connection open - how do I SEND that data to the DB before redirecting them to their destination site? They click - pass across this page - get redirected to destination.
BONUS KARMA - I also need a separate PHP file that I can create that PULLS from that data base. If you could point me at some instructions or show me a simple "how to pull this rows values from this table" I would be greatly appreciative :)
If I understand correctly, you'll want to use $_GET to get the URL parameters.
Then you want to run an insert query on the db with the values you got, which should be something like:
INSERT INTO table VALUES(x, y, z)
Then you need to change the page using a location header.
For the bonus question you just need the code you have now with a select query like:
SELECT * FROM table WHERE 1;
and then fetch the query results.
If this does not answer your questions please provide some clarifications.
Mysqli is the deprecated function and now PDO is recommended to connect to database. You could do following.
<?php
$conn = new PDO('dblib:host=your_hostname;dbname=your_db;charset=UTF-8', $user, $pass);
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $conn->query($sql);
?>
Read more here.
I am trying to insert data into two different tables in the same database, if I try to insert it into one database, it works, however, once I insert the second query into my code ($desc_query) it won't update any table.
Here is my code:
$name= strip_tags($_POST['name']);
$l_name= strip_tags($_POST['last_name']);
$c_id = strip_tags($_POST['company_id']);
$a_d = strip_tags($_POST['add_description']);
$d_t = strip_tags($_POST['desc_text']);
$connect = mysql_connect('localhost','id','pass') or die ("couldn't connect!");
mysql_select_db('database_db') or die('could not connect to database!');
//inserting names
$job_query=mysql_query("INSERT INTO names VALUES ('', '$name', '$l_name')");
//inserting a new description if needed. (this is the part that ruins everything)
if($a_d == 'true'){
$desc_query=mysql_query("INSERT INTO descriptions VALUES ('','$c_id','$d_t')");
}
You might be having an issue where some characters (like ' and ") are breaking the SQL query (not to mention opening your application up for SQL injection attacks).
I would recommend sanitizing all user provided data like so:
$name = mysql_real_escape_string(strip_tags($_POST['name']), $connect);
$l_name = mysql_real_escape_string(strip_tags($_POST['last_name']), $connect);
...
$d_t = mysql_real_escape_string(strip_tags($_POST['desc_text']), $connect);
Always operate under the assumption that the user is going to enter something outlandish or malicious that may (or may not) break your SQL.
Have you tried to echo out the queries and then to run them directly on the database?
Without any more information about the database we can't really tell if the queries themselves are valid.