I have the following codes:
$query = "INSERT INTO main_table (id, matric_no, session, semester,
course_name, test, exam,practical)
VALUES (NULL, '$_POST[matric_no]', '$_SESSION[session]',
'$_SESSION[semester]', '$_SESSION[course_name]', '$_POST[test]',
'$_POST[exam]', '$_POST[practical]')";
mysql_query($query) or
die (mysql_error());
Then I tried:
echo "$_POST[semester]";
echo "$_POST[course_name]" ;
and they echoed out what I was expecting but not INSERTing INTO the database.. Only those two.
Thanks.
As pointed out in the comments, the problem was a column type mismatch that wasn't visible in the original question.
However, it is a very bad idea to insert POST or other values directly - always run mysql_real_escape_string() (or whatever sanitation function your database library provides) on them. More on SQL injections here.
This code should give you a syntax error...
echo "$_POST[semester]";
echo "$_POST[course_name]" ;
Try this
echo "{$_POST['semester']}";
echo "{$_POST['course_name']}" ;
or this:
echo "xxx".$_POST['semester']."xxx";
echo "xxx".$_POST['course_name']."xxx;
More information here:
http://php.net/manual/en/language.types.string.php
Mind that $_POST[xxx] is note the proper syntax !!! Read docs above!
Related
I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.
The following code is responsible for the MySQL error Error In Insert-->Unknown column 'expert manager' in 'field list'. If I remove the code below it will solve the MySQL error. Do you know what's wrong with this piece of code?
$l=0;
$source = 'expertmanager';
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', ".$this->cat.", ".$course_id.",'".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, ".$close.", ".$source.")") or die("Error In Insert-->".mysql_error());
}
Thanks!
What is wrong with this piece of code:
Too short variable names
Don't use variable names that are shorter than 3-5 chars. Every variable name should describe the value(s) you want to store inside.
//bad
$l=0;
//good
$executionOrder = 0;
Concatenation of queries
Don't concatenate queries, it's a bad practice that leads to errors, insecure applications, etc. Don't use the mysql API either, it's outdated, insecure and will be deprecated. Use PDO and prepared statements instead.
//bad
mysql_query("DELETE FROM `student_questions` WHERE user_id=".$userId."");
//good
$statement = $db->prepare("DELETE FROM `student_questions` WHERE user_id = ?);
$statement->execute(array($userId));
Usage of die()
I see it all the time, and I see people telling other people to do that all the time. It's plain simply bad practice and it's time that people start to understand this. You cannot catch the error in any way. You cannot log the error. You cannot control whether it should be output to the screen or not. It's okay to do that in a development environment, but certainly not in a production environment.
You're vulnerable to SQL injection attacks
NEVER, NEVER include user data (session, get, post, cookie, etc.) unfiltered/unescaped into your queries.
//really bad
$query = "SELECT something FROM table WHERE " . $_POST['someValue'];
//better
$query = "SELECT something FROM table WHERE " . mysql_real_escape_string($_POST['someValue']);
//even better: use prepared statements as shown above
And finally the smallest thing that's wrong and the one that created your error
//bad
$query = "INSERT INTO `student_questions` (source) VALUES (expertmanager)"; //that's what you have
//better
$query = "INSERT INTO `student_questions` (source) VALUES ('expertmanager')";
Do you have a column called expert manager? If so, try changing the name to 'expert_manager' (without quotes), and see if that works.
You forgot quotes around several values in your insert statement :
for($i=0; $i < $count; $i++)
{
mysql_query("INSERT INTO `student_questions` (`user_id`, `checked_id`, `category_id`, course_id, `question`, `exe_order`, `time`,course_code, year, school, status, close, source) VALUES ('".$userId."', '".$_POST['checkbox'][$i]."', '".$this->cat."', '".$course_id."','".$_SESSION['question']."','".(++$l)."', '".$time."', '".$course_code."', '".$year."', '".$school."', 1, '".$close."', '".$source."')") or die("Error In Insert-->".mysql_error());
}
Not only $source, there are also : $course_id, $close, etc.
You have not enclosed the value of $source (which is the string expert_manager) in single quotes in your query.
mysql_query("INSERT INTO `student_questions` (...snip...) VALUES (...snip...'".$school."', 1, ".$close.", '".$source."')") or die("Error In Insert-->".mysql_error());
//------------------------------------------------------------------------------------------------------^^^^^^^^^^^^^^^^
We cannot see the value of $close, but if it is a string value rather than numeric, it should probably be enclosed in quotes as well.
Additional note: I see $_POST['checkbox'][$i] passed directly into the query. Please make sure this input has been properly validated and escaped with mysql_real_escape_string() if necessary. The same rule may apply to other variables used in the VALUES() list, but we cannot see their origins with the code posted.
<?php
ob_start();
$id=$_REQUEST['req-id'];
// #header("location:feed.php?tumblr_id=$id");
echo "aaaa";
include_once('../config/config.php');
echo $name=$_REQUEST['req-name'];
echo $id=$_REQUEST['req-id'];
echo $mobile=$_REQUEST['req-mobile'];
echo $Email=$_REQUEST['req-email'];
echo $select=$_REQUEST['image'];
echo $img=$_REQUEST['img'];
echo $audio=$_REQUEST['audio'];
echo $ado=$_REQUEST['ado'];
echo $regular=$_REQUEST['regular'];
echo $reg=$_REQUEST['reg'];
echo $video=$_REQUEST['video'];
echo $vdo=$_REQUEST['vdo'];
echo $link=$_REQUEST['link'];
echo $lnk=$_REQUEST['lnk'];
echo $quote=$_REQUEST['quote'];
echo $qte=$_REQUEST['qte'];
echo $fbPid=$_REQUEST['fbPid'];
$sql="update tumblr set (tumblr_name,tumblr_id,mobile_no,Email,img_post,link_post,ado_post,vdo_post,reg_post,qte_post) values('$name','$id','$mobile','$Email','$img','$lnk','$ado','$vdo','$reg','$qte')";
$res=mysql_query($sql) or die(mysql_error());
?>
I am getting 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 '(tumblr_name,tumblr_id,mobile_no,Email,img_post,link_post,ado_post,vdo_post,reg_' at line 1
UPDATE tumblr
SET tumblr_name = '$name',
tumblr_id = '$id',
mobile_no = '$mobile',
Email = '$Email',
img_post = '$img',
link_post = '$lnk',
ado_post = '$ado',
vdo_post = '$vdo',
reg_post = '$reg',
qte_post = '$qte'
You are trying to execute an update query based on an insert's format. Check the update query format.
In addition, your code is HIGHLY insecure. At least use mysql_real_escape_string(), e.g. $name=mysql_real_escape_string($_REQUEST['req-name']); to protect against SQL injection.
You are confusing the insert syntax with the update syntax. The update syntax is detailed here: http://dev.mysql.com/doc/refman/5.0/en/update.html
Example:
UPDATE table
SET
col1 = value1,
col2 = value2
WHERE
...
You are using INSERT syntax in an UPDATE statement.
Update looks like this:
UPDATE tableone SET fieldone='one' WHERE id=2;
For example.
UPDATE syntax is
UPDATE `tablename` SET `column`=value, `column`=value, ... WHERE conditions
u use INSERT syntax.
And what have you done to diagnose the problem?
Showing us all those echo statements doesn't really help - it might have done if you'd told us what the values were. You're not escaping any of the values you are putting in your SQL statement. You seem to be quoting values which may be numeric. You've included an ob_start() statement which is also entirely irrelevant but there's no mysql_connect here.
But the reason your code is failing is because there is no 'UPDATE....VALUES...' statement in SQL. Use 'INSERT INTO...VALUES....ON DUPLICATE KEY UPDATE'.
$db = mysql_connect("localhost","root","123");
mysql_select_db("website_categorization") or die("\n error selecting database" );
$keyword_array = preg_split('/[\s,]+/', $tag);
foreach($keyword_array as $tag1)
{
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,$tag1)");
}
echo "\nAffected rows are ".mysql_affected_rows()."\n";
mysql_close($db);
Can u tell me what is the problem with this code??...I intend to insert rows into the category_keyword table from an array $keyword_array. I get errors "Affected rows are -1" and insertion does not work
You should quote and escape string values.
You should also handle errors, to be notified of them.
You should also write distinct statements, to be able to read your code later (as well as let others to read it).
$tag1 = mysql_real_escape_string($tag1);
$sql = "INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'$tag1')";
mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
insert multiple rows via a php array into mysql
You need to encapsulte the string $tag in a query, otherwise mysql will think its a column name
mysql_query("INSERT INTO category_keyword(ID_Category, Keyword) VALUES(2,'".mysql_real_escape_string($tag1)."')");
You should quote and escape your string columns
$tag1 =
mysql_real_escape_string($tag1);
mysql_query("INSERT INTO
category_keyword(ID_Category, Keyword)
VALUES(2,'$tag1')");
You should also handle the mysql query errors to know why the query get failed. With the current code you never know why it is failing.It is better to handle mysql errors.
mysql_query('Your query') or trigger_error(mysql_error());
You can use this:
mysql_query("INSERT INTO category_keyword SET ID_Category=2, Keyword=".$tag1.");
Better syntax to understand :)
i have the following error
insert into staff_service(customer_id,workorder_no,service_date,current_date) values('1','414','2011-03-14',CURDATE()) 1064 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 'current_date) values('1','414','2011-03-14',CURDATE())' at line 1
<?php
session_start();
include "common/config.php";
$file=file("Template/staffservice_management.html");
$filecontent=join("",$file);
include("user.php");
/*$sql = "SELECT id,customer_name FROM customer "."ORDER BY customer_name";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['id']."\">".$row['customer_name']."</option>";
echo "<option value=\"".$row['id']."\">".$row['customer_name']."</option>";
echo "<option value=\"".$row['id']."\">".$row['customer_name']."</option>";
}*/
$sql="select * from customer";
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$list_option.="<option value='".$row['id']."'>".$row['customer_name']."</option>";
}
$cust=$_POST['cname'];
$work=$_POST['won'];
$date=$_POST['startdate'];
if($_REQUEST['submit']=='submit')
{
$sqle=("insert into staff_service(customer_id,workorder_no,service_date,current_date) values('$cust','$work','$date',CURDATE())");
$Insertprocess=$db->insert_data_id($sqle);
echo "<script>alert(' Details Successfully created');</script>;";
echo "<script>location.href='staffservice_management.php';</script>;";
}
$filecontent=preg_replace("/{{(.*?)}}/e","$$1",$filecontent);
echo $filecontent;
?>
Don't interpolate variables straight into your SQL, you're asking for SQL injection attacks. Take a look at http://www.bobby-tables.com/
As for the error, there's no space after the table name, that's the likely culprit; it's being treated as a call to an unknown function, staff_service().
insert into staff_service (customer_id,workorder_no,service_date,current_date) values('$cust','$work','$date',CURDATE())
leave space after table name
I guess you need an space between
staff_service
and
(customer_id,workorder_no,service_date,current_date)
Try with:
$sqle=("insert into staff_service (customer_id,workorder_no,service_date,current_date) values('$cust','$work','$date',CURDATE())");
HTH!
INSERT INTO staff_service
(customer_id,workorder_no,service_date,current_date)
VALUES ('1','414','2011-03-14',CURDATE())
There are a couple of questions about Data Types:
What is the data type of customer_id?
if it is a INT data type, no need for the single quotes around the value 1
EXAMPLE: VALUES (1,'414','2011-03-14',CURDATE())
What is the data type of workorder_no?
if it is a INT data type, no need for the single quotes around the value 414
EXAMPLE: VALUES ('1',414,'2011-03-14',CURDATE())
What is the data type of service_date?
If it's a date/time type are you submitting the correct format?
Other formats
What is the data type of current_date?
If it's a date/time type are you submitting the correct format?
Other formats
You might want to end you SQL statement with a semicolon as well, like this:
INSERT INTO staff_service
(customer_id,workorder_no,service_date,current_date)
VALUES ('1','414','2011-03-14',CURDATE());
My suggestions are to make sure you are passing the data in the correct format
You do not need to use " ' " for numbers/ids:
insert into staff_service(customer_id,workorder_no, service_date,current_date) values(1,414,'2011-03-14',CURDATE())
Add a semicolon at the end of the SQL query.