Insert data from 1 form into 2 Mysql DBs - php

I am trying to use one form to insert data into 2 tables.
I have one table, Members and another, Members.
Here is my code:
<?php
$first_name=$_POST[first_name];
$last_name=$_POST[last_name];
$email_address=$_POST[email_address];
$staff=$_POST[staff];
$type=$_POST[type];
$descr=$_POST[descr];
$time=$_POST[time];
mysql_select_db("cl49-vogclients", $con); $sql="INSERT INTO member
(first_name,last_name,email_address)
VALUES
('$first_name','$last_name','$email_address')";
if (!mysql_query($sql,$con)) { die('Error adding client ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Client Added Succesfuly</font> </h2>';
$sql1="INSERT INTO audit
(staff,type,descr)
VALUES
('$staff','$type','$descr')";
if (!mysql_query($sql1,$con)) { die('Audit Unsucsessful ' . mysql_error()); } mysql_close($con);
echo' <h2><font color="green">Audit Succesful</font> </h2>';
This adds the client/member but not add anything to the audit database?

This is because you are only executing the first query:
mysql_query($sql,$con)
You have to call it seperatly for $sql1
Besides that: Please bear in mind that mysql like this is heavily outdated and deprecated. You should really look into PDO and prepared statements.
http://php.net/manual/de/book.pdo.php

You have closeds SQL
You need to remove mysql_close($con);

Related

how to use insert values into database using php

$value2=$_POST['c_name'];
$value3=$_POST['c_vehicle_number'];
$value4=$_POST['c_phone'];
$value5=$_POST['c_email'];
these are the values stored in 1.php.
i want insert those values in 2.php.as below,
$sql="insert into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) values ('','$value2','$value3','$value4','$value5')";
=====================================================
am using require('1.php');
which does not insert the values into the database.
what would be the soluton.?
In order to enter a values into the DB one must have a connection to the Database.
Create a connection to the relevant database.
Perform our desired query.
Example:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Explanation:
As you can see we first trying to retain a connection using mysqli_connect with the relevant DATABASE-ADDRESS, USERNAME, PASSWORDandDATABASE-NAME`
Than we're using mysqli_query to perform our query and we're passing it the connection we opened earlier + the query string we wish to perform.
More explanation could be found HERE
Important: This example isn't SQL-Injection protected, and it's highly important to you, to be protected against it. Read about it HERE
you can try this
$sql="INSERT into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) VALUES ('".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."')";
you worte :
('','$value2','$value3','$value4','$value5') you did mistake here
it can be write
('".$value2."','".$value3."','".$value4."','".$value5."')

MySQL Database Specific Top (Amount)

I recently began learning PHP, and I set up a MySQL Server. However, I'm not very familiar with SQL, and I would like to know, how would I get the top amount of results (amount as defined by _GET["Amount"] that all have the same EventType as defined by _GET["EventType"]?
<?php
$con=mysqli_connect(Info removed);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Amount=$_GET["Amount"];
$GetType=$_GET["Type"];
$sql= ""; //How would I do the action outlined above?
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Done";
mysqli_close($con);
?>
I've looked over this site and others, to no avail. All help is greatly appreciated.
Sorry misunderstood your question...
Try this instead: $sql = "SELECT * FROM table WHERE EventType='$GetType' ORDER BY amount_column DESC";
Run the query: $sql_run = mysql_query($sql);
The amount column in your table do have to be INT i think.
To echo out all the amounts you could then say something like:
while($sql_row = mysql_fetch_assoc($sql_run)){
echo $sql_row['amount_column'].'<br>';
}
btw in your code you don't use the mysql_select_db() method, there might be a way around it, but as far as I know you do have to specify a database.
Before writing query you need to prepare the mysql table. If you have one, try to post here your table structure.

Can not send information from PHP form to multiple mysql database tables

I am trying to insert data into 4 tables ( asset, asset_details, invoice and location). When I submit the form, it tells me that all the data has been submitted successfully but when I check the MySQL database the information is only submitted to the location tables.
Any help will be appreciated, Thank you .
mysql_query("START TRANSITION");
$query1 =("INSERT INTO .asset (asset_tag, asset_number, cap_ex, asset_type_id, invoice_id, status)
Values(".$_POST['asset_tag'] .",,,".$_POST['asset_type'] . ",".$_POST['invoice_number']."," . $_POST['status_id'] .")");
$query2 =("INSERT INTO .asset_details (asset_type_id, asset_tag, asset_type, physical_asset_id, manufacturer, os, os_version, make, model, serial_number, processor, ram, memory, hdd, host_name, notes)
Values(" .",".$_POST['asset_tag']."," .$_POST['asset_type'].",,
,".$_POST['os'].",".$_POST['os_version'].",".$_POST['make'].",".$_POST['model'].",".$_POST['serial_number'].",".$_POST['processor'].",,".$_POST['memory'].",".$_POST['hdd'].",,".$_POST['notes'].")");
$query3 =( "INSERT INTO .invoice (invoice_number, invoice_date, purchas_price, quantity, order_date, vender, warrenty_end, notes)
Values(" .$_POST['invoice_number'].",". $_POST['invoice_date'].",". $_POST['purchase_price'].",,,". $_POST['vender'].")");
$query4 =( "INSERT INTO .location (location_name, rack, row, unit)
Values(" .$_POST['location_name'].",".$_POST['rack'].",".$_POST['row'].",".$_POST['unit'].")");
echo "$query1 $query2 $query3 $query4";
$result1= mysql_query($query1);
$result2= mysql_query($query2);
$result3= mysql_query($query3);
$result4= mysql_query($query4);
$result = mysql_query("COMMIT");
if (!$result)
{
mysql_query("ROLLBACK");
die('Invalid query: ' . mysql_error());
}
else
{
echo "<script>alert('SUCCESS!');</script>";
}
}
mysql_close($con);
?>
There are some strange things;
START TRANSITION should probably be START TRANSACTION.
You're not quoting any of your string values. Strings need to be quoted using ' a'la INSERT INTO TEST VALUES ('olle');
An empty field cannot be indicated by just skipping it, you're doing INSERT INTO TEST (a,b,c) VALUES (1,,2); which is not valid syntax for not setting b.
Also, I recommend using a more modern mysql api than mysql_query, as for example PDO or mysqli, since injecting POST values into a string as you do can be pretty dangerous, you may cause SQL injection problems.
Use '`'s around each attributes(columns) and ''' around each values, it should work
During development, I'd echo each query-expressions before it is sent to the database..
...by the way, mysql_error() is a useful function in php, which returns the last error information of mysql....U may use that for debugging

mySQL query syntax error?

I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The jquery script that sends it works, and the mail is sent, but this doesn't save.
Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.
Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.
SQL injection example:
"INSERT INTO table (field) VALUE ('$_POST[var]')"
If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.
and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.
http://php.net/mysql_real_escape_string
http://php.net/pdo
Your SQL request should be written as below:
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"
SQL fields using non-alphanumeric characters have to be escaped with backticks (`)
This should work
<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
die('Could not connect: '.mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
mysql_real_escape_string($_POST['Puhelin'])."','".
mysql_real_escape_string($_POST['Sposti'])."','".
mysql_real_escape_string($_POST['Tiedot'])."','".
mysql_real_escape_string($_POST['Gotcha'])."','".
mysql_real_escape_string($_POST['Day'])."')";
if(!mysql_query($sql, $con)){
die('Error: '.mysql_error());
}
echo "1 record added";
mysql_close($con);

PHP not inserting some values into MySQL database

I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left blank and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [blank]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
Well it will insert the final value only , because you are executing the $sql and the last values of $sql is "INSERT INTO scores (result) VALUES ('$_POST[result]')"; You are overiding the previous values by putting same variable name.
Also (!empty($_POST[hometeam])) remove the !empty if the fields can be blank sometimes.
You are overwriting your SQL statements each time. Beacue your 'result' field isn't blank, you are setting your SQL statement to:
"INSERT INTO scores (result) VALUES ('$_POST[result]')"
This is the only statement which is then being executed - your other values are being ignored as they are not part of this statement.
What you need to do is set up your variables first:
$hometeam = isset($_POST['hometeam']) ? $_POST['hometeam'] : NULL;
$awayteam = isset($_POST['awayteam']) ? $_POST['awayteam'] : NULL;
$result = isset($_POST['result']) ? $_POST['result'] : NULL;
You can then do your database interaction:
$sql = "INSERT INTO scores hometeam, awayteam, result VALUES $hometeam, $awayteam, $result";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
I should say that I haven't included any security on this - you should look into PDO or prepared statements to make sure your database isn't open to SQL Injection.
Hope this helps!
First off, there's a huge security flaw in this code, which is not sanitizing your inputs. A user could insert whatever they like and it's executed on the DB without any checking. This is bad.
At the very least, you should be using something like mysql_real_escape_string(), even though even that is not exactly the best thing for the job (Google PHP + PDO for example).
Secondly, you're actually executing one query using one variable. If $_POST['result'] is set, then $sql will always be the last value. What you might want to do is make the query like so:
$query = 'INSERT INTO scores ('.$fields.') VALUES ('.$values.')';
And construct the $fields and $values variables using your if(!empty( .. )) code.
But to reiterate SANITIZE YOUR INPUTS
3 insert into statements will insert 3 records, with unspecified fields left as null or default.
you must use 1 insert into statement, something like:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
#$sql="INSERT INTO scores (hometeam,awayteam,result) VALUES ('{$_POST[hometeam]}','{$_POST[awayteam]}','{$_POST[result]}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
here, unspecified values will come as empty string, if that is a problem, first assign them to 3 seperate variables with ifs (e.g. set empty ones to null), then use them
I think there is some problem with the declaration of name of your input field in you html form. Make sure, $_POST[hometeam] must be the same input name in your form
Example:
In your form
<input type="text" name="hometeam" value="" />
In your PHP
if (!empty($_POST[hometeam])) {
$sql="INSERT INTO scores (hometeam) VALUES ('$_POST[hometeam]')";
}
And also, please use addslashes or mysql_real_escape_string in your post values before adding it on the database.
Look at this link below:
http://php.net/manual/en/function.addslashes.php
http://php.net/manual/en/function.mysql-real-escape-string.php
if (!empty($_POST['hometeam'])) {
$sql="INSERT INTO scores (hometeam) VALUES ('" . $_POST['hometeam'] . "')";
}
Notice the single quotes around the 'hometeam' part.
You should also clean that using mysql_real_escape_string($_POST['hometeam']).
Bear in mind this will create upto 3 rows for each call, if you want to have a row like scores (hometeam, awayteam, result) you'll need to construct your query differently (i.e. a single query not 3 seperate ones).

Categories