Storing Data to MySQL database from html form with checkboxes - php

I have an html form with checkboxes and I managed to store the values using an array to my database .
I added a name field to the form, and added a column on mysql table .
The problem is, the newly added name field is not storing any values and is malfunctioning the previous code. I'm pretty sure my definition for the $fname value is incorrect, here is the full php code
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
if (!$dbcon) {
die('error connecting to database'); }
echo 'Courses successfully registerd , ' ;
// escape variables for security
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$fname = $_POST["name"];
// Get Cources
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courcess){
$cc=$cc. $courcess.',';
}
}
//$ckb = join (', ', var_dump($_POST['ckb']));
$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
if (!mysqli_query($dbcon,$sql)) {
die('Error: ' . mysqli_error($dbcon));
}
echo " Thank you for using IME Virtual Registeration ";
mysqli_close($dbcon);
?>

$sql="INSERT INTO courses (studentid, ckb)
VALUES ('$studentid', '$cc', $fname)";
is your problem. You are attempting to insert three values into two fields. You need to add your new field after ckb so that the argument $fname can be inserted into it.

Related

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}

PHP ~ Column count doesn't match value count at row 1

Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();

Copy value to another table

I have a problem with my code. I have a table called "users" with an "id" field.I want to copy the id value to another table called "aircondition" . This is the code that inserts values into the aircondition table .The problem is that when I use this code I get 0 in the new id field instead of the user.id
<?php
$con=mysqli_connect("localhost","george","george123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
VALUES ('SELECT id
FROM users', '$acname', '$btu', '$space', '$energyclass')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
Use this query
INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users

Multiple insert issue

When I use this code, I get one record for each id stored in the users table. Instead, I want to be able to insert only 1 record each time, the one that matches the logged users id.
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$acname = mysqli_real_escape_string($con, $_POST['ACName']);
$btu = mysqli_real_escape_string($con, $_POST['BTU']);
$space = mysqli_real_escape_string($con, $_POST['Space']);
$energyclass = mysqli_real_escape_string($con, $_POST['EnergyClass']);
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
header('location:aircondition.php');
mysqli_close($con);
?>
You must have a where clause in your select statement
$sql="INSERT INTO aircondition (id, ACName, BTU, Space, EnergyClass)
SELECT id, '$acname', '$btu', '$space', '$energyclass'
FROM users WHERE usernamecolumn= currentusername ;

Insert output data to database of an web page

i have a output page of the following php code..
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
the output value of the script is to be inserted in to the database like MySQL.
for that i try something like that..
<?php
// example of how to use basic selector to retrieve HTML contents
include('../simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('http://www.wine-searcher.com/merchant/852');
$data=$html->find('td.firstcell');
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE nt_usawine",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("nt_usawine", $con);
$sql = "CREATE TABLE Persons
(
FirstName varchar(15),
LastName varchar(15),
Age int
)";
// Execute query
mysql_query($sql,$con);
$foo= $data[2];
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)");
mysql_close($con);
echo "Country :". $data[0].'<br />';
echo "Email :".$data[2].'<br />';
echo "Postal Address :".$data[3].'<br />';
echo "Permanent Address :".$data[4].'<br />';
echo "Contact :".$data[10].'<br />';
but still i cant get the table in the database with my data inserted. what is the right way to save the data ?
Have you tried to debug this by using mysql_error ?
$query = "INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin', $foo)";
$result = mysql_query($query);
if (!$result) {
$message = 'There is an error : ' . mysql_error() . "\n";
$message .= 'The query was : ' . $query;
die($message);
}
If you have an SQL error this would be very usefull.
By the way have you seen the only once time you don't do mysql_query( [...], $con) it the once which should add datas ?
And is it normal that you create a database and a table each time ? (don't know what you really want to do)
The mysql_query(); function allows you to run a query. Using the INSERT syntax you can insert data.
Example:
mysql_query("INSERT INTO `table` (`column1`, `column2`) VALUES ('value1', 'value2')");
Currently, what I'm seeing you wish to insert the country, email, postal address, permanent address and contact even though you create a table that can hold the data firstname, lastname and age...
No offence, but if you're already stuck there, this is not the right place to post your question. You need to search some tutorials before you even consider asking. SQL queries are well documented and can be found all over the web.
Either way, I'm too kind to leave this question unanswered.
I advice to create your database and table in PhpMyAdmin, rather creating a new one in your script. It's rather inefficient.
<?php
// this is where you login to your database
$connection = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
// select your EXISTING database you created. Usually there's a single database linked to your website
mysql_select_db('database_name', $connection);
// inserting data into table
$success = mysql_query("INSERT INTO `table_name` (`country`, `email`, `postaladdr`, `permanentaddr`, `contact`) VALUES ('".mysql_real_escape_string($data[0])."', '".mysql_real_escape_string($data[2])."', '".mysql_real_escape_string($data[3])."', '".mysql_real_escape_string($data[4])."', '".mysql_real_escape_string($data[10])."')");
// check if insert was successful
if($success) {
echo 'data inserted';
} else {
echo 'Something went wrong: ' . mysql_error();
}
// closing database
mysql_close($connection);
?>
Now all you have to do is change the login data, change the database_name, create the actual table and change the table_name in the script.
This is one of the first things you learn when starting with running SQL queries, so I higly suggest to learn more: http://www.w3schools.com/php/php_mysql_intro.asp
If everything I said didn't make any sense, you should click the link above.

Categories