How to insert multiple checkboxed answers into a database table? - php

I'm having a huge issue with this database. It connects correctly and with the information from the form's $_POST queries that are being inserted into the table company_info within the correct fields.
Now, I have no idea what I'm doing wrong here, but I keep getting the die error of
"Error querying database".
The database version is: phpMyAdmin 2.6.4-pl3
MySQL: 5.0
Any ideas? I can provide you the rest of the code if needed.
$dbc = mysql_connect('db390590179.db.1and1.com', 'dbo390590179', '*********')
or die('Error connecting to MySQL server.');
mysql_select_db("db390590179", $dbc);
$query = "INSERT INTO company_info (company_name, company_phone, company_contact, company_address, " .
"company_city, company_state, company_zip, " .
"state_living, vehicles, position, " .
"experience, training, hazmat, " .
"require_hazmat, load_nyc, take_truck_home, " .
"have_rider, have_pet, choose_route, " .
"fuel, cash_advance, days_before_home, " .
"log_system, slip_seat, pre_pass, " .
"ez_pass, health_insurance, retirement_plan, " .
"payment_plan, calculate_pay, freight, " .
"loads, home_on_time, idle_time, " .
"equipment_condition, canada)" .
"VALUES ('$company_name', $company_phone', '$company_contact', '$company_address', '$company_city', " .
"'$company_state', '$company_zip', " .
"'$state_living', '$vehicles', '$position', " .
"'$experience', '$training', '$hazmat', " .
"'$require_hazmat', '$load_nyc', '$take_truck_home', " .
"'$have_rider', '$have_pet', '$choose_route', " .
"'$fuel', '$cash_advance', '$days_before_home', " .
"'$log_system', '$slip_seat', '$pre_pass', " .
"'$ez_pass', '$health_insurance', '$retirement_plan', " .
"'$payment_plan', '$calculate_pay', '$freight', " .
"'$loads', '$home_on_time', '$idle_time', " .
"'$equipment_condition', '$canada')";
$result = mysql_query($query, $dbc)
or die('Error querying database.');
mysql_close($dbc);

I think it's because it's missing a quote before the variable $company_phone in your INSERT statement.

just combine the different values within a single quote.
E.g., "'$company_state , $company_zip,' " ."'$state_living , $vehicles, $position, '" ."'$experience, $training, $hazmat, '" ....
this will work perfectly and also include the missing quote in the begining of the *$company_phone* has to be included.

You can remove double quote from each line and combine them. I have removed syntax errors. You can assure that result is getting or not. Try this code.
$dbc = mysql_connect('db390590179.db.1and1.com', 'dbo390590179', '*********')
or die('Error connecting to MySQL server.');
mysql_select_db("db390590179", $dbc);
$query = "INSERT INTO company_info (company_name, company_phone, company_contact, company_address,
company_city, company_state, company_zip,
state_living, vehicles, position,
experience, training, hazmat,
require_hazmat, load_nyc, take_truck_home,
have_rider, have_pet, choose_route,
fuel, cash_advance, days_before_home,
log_system, slip_seat, pre_pass,
ez_pass, health_insurance, retirement_plan,
payment_plan, calculate_pay, freight,
loads, home_on_time, idle_time,
equipment_condition, canada)
VALUES ('$company_name', '$company_phone', '$company_contact', '$company_address', '$company_city',
'$company_state', '$company_zip',
'$state_living', '$vehicles', '$position',
'$experience', '$training', '$hazmat',
'$require_hazmat', '$load_nyc', '$take_truck_home',
'$have_rider', '$have_pet', '$choose_route',
'$fuel', '$cash_advance', '$days_before_home',
'$log_system', '$slip_seat', '$pre_pass',
'$ez_pass', '$health_insurance', '$retirement_plan',
'$payment_plan', '$calculate_pay', '$freight',
'$loads', '$home_on_time', '$idle_time',
'$equipment_condition', '$canada')";
$result = mysql_query($query, $dbc)
or die('Error querying database.');
mysql_close($dbc);

for (int i = 0; i < CheckBoxList1.Items.Count - 1; i++)
{
String str = "";
if (CheckBoxList1.Items[i].Selected)
{
str = CheckBoxList1.Items[i].Text;
con.Open();
string sql =
"Insert into dbtable(Category,BookTitle,Feature,SubCategory)values('" +
DDLCategory.SelectedItem.Text + "','" + TxtBooktitle.Text + "','" +
CheckBoxList1.Items[i].Text + "','" + DDLSubcategory.SelectedItem.Text +
"')";
SqlCommand cmd = new SqlCommand(sql, con);
}
}
Just use DEBUGGER and see how things are working and you should be able to resolve such issues easily.

Related

How can I get the number of rows in a MySQL table with PHP?

Why is my code returning a 500 Internal Server error on the line $result = mysql_query("SELECT * FROM institutions"); Am I doing something horrifically wrong? All I am trying to do is count the number of rows in a MySQL table (called 'institutions') after I have just added a row to that table.
$institution_sql = "
INSERT INTO `institutions`
(`InstitutionName`, `HeaderPictureID`, `Description`, `DevicesInfo`, `DoingInfo`, `FacebookPage`, `Location`, `TwitterHandle`, `Website`, `CreatedAt`)
VALUES
(" . nz($_POST['TempInstitutionName']) . ", 74, 'N/A', 'N/A', 'N/A', 'N/A', 'On the Internet', 'N/A', 'N/A', NOW())
";
$mysqli->query($institution_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$result = mysql_query("SELECT * FROM institutions");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
$insert_sql = "
INSERT INTO `users`
(`Handle`, `Email`, `FirstName`, `LastName`, `InstitutionID`, `TempInstitutionName`, `TwitterHandle`, `ProfilePictureID`, `HeaderPictureID`, `AccountType`, `CreatedAt`)
VALUES
(" . nz($_POST['Handle']) . ", " . nz($_POST['Email']) . ", " . nz($_POST['FirstName']) . ", " . nz($_POST['LastName']) . ", $num_rows, " . nz($_POST['TempInstitutionName']) . ", " . nz($_POST['TwitterHandle']) . ", " . nz('75') . ", " . nz('74') . ", " . nz($_POST['AccountType']) . ",NOW())
";
$mysqli->query($insert_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "EXEC_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$insertid = $mysqli->insert_id;
$password_sql = "
INSERT INTO `passwords`
(`UserID`)
VALUES
('$insertid')
";
$mysqli->query($password_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
}
} //todo: use a transaction here
}
your problem is that you mixing MYSQLI with MYSQL
rewrite your code using mysqli
$result = $mysqli->query("SELECT * FROM institutions");
$rows = $result->num_rows ;
// and so on ...
you are connecting via mysqli and then you use mysql in your code.
$result = mysql_query("SELECT count(*) FROM institutions");
This will directly return the number of rows.
This link can detail you
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Use
$result = $mysqli->query($institution_sql);
$result->num_rows;
Or for plain old mysql
$result = mysql_query($institution_sql);
mysql_num_rows($result);
Try this:
$result = mysql_query("SELECT count(*) FROM institutions");
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Also this: http://www.w3schools.com/sql/sql_func_count.asp
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
...also, that should be:
VALUES
('" . nz($_POST['TempInstitutionName']) . "', 74
Note the single quotes [unless the 'nz' function takes care of that].

Multiple SQL statements causing error, via PHP

I am trying to make a php calendar, as part of a project, and here I am executing some SQL with php:
mysql_select_db("waycov_dtm", $con);
$data="'Placeholder Text'";
$sql="INSERT INTO waycov_dtm.calDates (dateID, day, month, year)
VALUES (" . $dateID . ", " . $day . ", " . $month . ", " . $year . ");
INSERT INTO waycov_dtm.calData (dateID, data, memberID)
VALUES (" . $dateID . ", " . $data . ", 1);";
echo $sql;
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
When this executes, I get the following (the echoed sql and then the error):
INSERT INTO waycov_dtm.calDates (dateID, day, month, year) VALUES (7072012, 7, 07, 2012); INSERT INTO waycov_dtm.calData (dateID, data, memberID) VALUES (7072012, 'Placeholder Text', 1);Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO waycov_dtm.calData (dateID, data, memberID) VALUES (7072012, 'Placeh' at line 3
If i take out any one insert statment, the other runs, but both together causes this??
Use it like this:
$sql="INSERT INTO waycov_dtm.calDates (dateID, day, month, year)
VALUES (" . $dateID . ", " . $day . ", " . $month . ", " . $year . ")";
$sql_second = "INSERT INTO waycov_dtm.calData (dateID, data, memberID)
VALUES (" . $dateID . ", " . $data . ", 1);";
if (!mysql_query($sql,$con) || !mysql_query($sql_second,$con))
{
die('Error: ' . mysql_error());
}
From the manual:
mysql_query() sends a unique query (multiple queries are not
supported)
The use of mysql_query is discouraged. Use MySQLi or PDO.

Insert into mysql and php using array

I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT

unknown column error in insert mysql query in php?

Despite reading quite many posts i cannot solve this error-
Unknown column 'alt.atheism1111' in 'field list'
the fields filename,category may have . in the middle of numbers or words,
im using phpmyadmin for database
function insert_rec($cat,$file,$wordid,$synsetid,$seqno)
{
$cat=mysql_real_escape_string($cat);
$file=mysql_real_escape_string($file);
$wordid=mysql_real_escape_string($wordid);
$synsetid=mysql_real_escape_string($synsetid);
$seqno=mysql_real_escape_string($seqno);
echo $cat." ". $file ." ". $wordid." " . $synsetid." " . $seqno;
$sql="INSERT INTO `wordnet50`.`table` (`category`,`filename`,`wordid`,`synsetid`,`seqno`) VALUES (`" . $cat . "`,`" . $file. "`,`" . $wordid. " `,`" . $synsetid . "`,`" .$seqno . "`)";
$result=mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
}
$sql="INSERT INTO `wordnet50`.`table` (`category`,`filename`,`wordid`,`synsetid`,`seqno`) VALUES (`" . $cat . "`,`" . $file. "`,`" . $wordid. " `,`" . $synsetid . "`,`" .$seqno . "`)";
You need to remove "`" from the above query in the values only and replace it with " ' " (single quote)
Use backticks for field names and single quotes for the values.
$sql = "INSERT INTO `wordnet50`.`table` (`category`,`filename`,`wordid`,`synsetid`,`seqno`)
VALUES ('$cat', '$file', '$wordid', '$synsetid', '$seqno')";
It should be wrapped with single quotes not with back tick.
$sql = "INSERT INTO `wordnet50`.`table` (`category`,`filename`,`wordid`,`synsetid`,`seqno`) VALUES ('" . $cat . "','" . $file. "','" . $wordid. "','" . $synsetid . "','" .$seqno . "')";
BackTick escapes MYSQL Reserved WORDS.
if u can post ur db schema than it will be easy to check, as of now it look like u have a field as alt.atheism1111 which can be the show stopper
or use this:
$sql = "INSERT INTO `wordnet50`.`table` (`category`,`filename`,`wordid`,`synsetid`,`seqno`)
VALUES ('$cat', '$file', '$wordid', '$synsetid', '$seqno')";

Can't Update MySQL table

I don't know what I'm doing wrong, but my little update code is giving me an error message that I can't work out how to resolve it.
Here's my code:
<?php
include('dbconfig.php');
$con = mysql_connect($host, $username, $password) or die(mysql_error()) ;
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
function sqlEscape($string){
return "'".mysql_real_escape_string($string)."'";
}
if(isset($_POST['submit'])){
$q = "UPDATE records SET `name` = " + sqlEscape($_POST['name']) + ",
`age` = " + sqlEscape($_POST['age']) + ",
`location` = " + sqlEscape($_POST['location']) + ",
`telephone` = " + sqlEscape($_POST['telephone']) + "
WHERE id = $_POST[id]";
mysql_query($q) or die(mysql_error());
}
?>
Here's the error message it prints out:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0' at line 1
Can someone see where I'm going wrong at all?
Thanks for your help.
You are adding strings together with the + operator, which is for adding numbers. In PHP, strings are concatenated with the . (period) operator.
$q = "UPDATE records SET `name` = " . sqlEscape(...) . ",
etc
$q = "UPDATE records SET `name` = " . sqlEscape($_POST['name']) . ",
`age` = " . sqlEscape($_POST['age']) . ",
`location` = " . sqlEscape($_POST['location']) . ",
`telephone` = " . sqlEscape($_POST['telephone']) . "
WHERE id = $_POST[id]";
Use "." instead of "+" to concat strings in PHP.

Categories