Failed to add record to database - php

I'm sitting with this code for about 2 hours and I still dont know why it isnt working. Check this:
mysql_query("INSERT INTO newsy (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) VALUES ($tytul, $autor, $skrot, $opis, $data, $extra, $kategoria, $wartosc_extra, $jednostka, $stan_magazynowy)");
Every variable is correctlly passed and I can check all with echo, so the problem is here but I dont know exactly where. Thanks for your help

You're probably inserting strings, and have forgotten to quote them, e.g.
INSERT INTO newsy (tytul, ...) VALUES ('$tytul', ....)
^-- ^---
assuming you're using the deprecated mysql_*() functions, you would have noticed this if you had any sort of error handling on your queries:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^

Seems like you have 12 columns in (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) and you are trying to insert only 10 values.

you are missing quotes around your variables, please change to this
mysql_query("INSERT INTO newsy (tytul, skrot, opis, cena, opinia, galeria, data_utw, extra, kategoria, wartosc_extra, jednostka, stan_magazynowy) VALUES ( '".$tytul."', '".$autor."', '". $skrot."', '".$opis."', '".$data."', '".$extra."', '".$kategoria."', '".$wartosc_extra."', '".$jednostka."', '". $stan_magazynowy."')");
The query will fail anyway since there are 12 fields and 10 variables to insert
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO

First pass 12 value instead of 10
and surround value with single quote(') like '$tytul'

Related

Mysql insert using array

I have an array stored in a variable $contactid. I need to run this query to insert a row for each contact_id in the array. What is the best way to do this? Here is the query I need to run...
$contactid=$_POST['contact_id'];
$eventid=$_POST['event_id'];
$groupid=$_POST['group_id'];
mysql_query($query);
$query="INSERT INTO attendance (event_id,contact_id,group_id) VALUES ('$eventid','$contactid','$groupid')";
Use a foreach loop.
$query = "INSERT INTO attendance (event_id,contact_id,group_id) VALUES ";
foreach($contactid as $value)
{
$query .= "('{$eventid}','{$value}','{$groupid}'),";
}
mysql_query(substr($query, 0, -1));
The idea here is to concatenate your query string and only make 1 query to the database, each value-set is separated by a comma
Since no one hasn't stated that yet, you actually cannot do this:
$query = '
INSERT INTO [Table] ([Column List])
VALUES ([Value List 1]);
INSERT INTO [Table] ([Column List])
VALUES ([Value List 2]);
';
mysql_query($query);
as this has been prevented to prevent sql injections in the mysql_query code. You cannot have semicolon within the given query param with mysql_query. With the following exception, taken from the manual comments:
The documentation claims that "multiple queries are not supported".
However, multiple queries seem to be supported. You just have to pass
flag 65536 as mysql_connect's 5 parameter (client_flags). This value
is defined in /usr/include/mysql/mysql_com.h:
#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */
Executed with multiple queries at once, the mysql_query function will
return a result only for the first query. The other queries will be
executed as well, but you won't have a result for them.
That is undocumented and unsupported behaviour, however, and easily opens your code to SQL injections. What you can do with mysql_query, instead, is
$query = '
INSERT INTO [Table] ([Column List])
VALUES ([Value List 1])
, ([Value List 2])
[...]
, ([Value List N])
';
mysql_query($query);
so you can actually insert multiple rows with a one query, and with one insert statement. In this answer there's a code example for it which doesn't concatenate to a string in a loop, which is better than what's suggested in this thread.
However, disregarding all the above, you're probably better of still to use a prepared statement, like
$stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
foreach($myarray as $row)
{
$stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
$stmt->execute();
}
$stmt->close();
Use something like the following. Please note that you shouldn't be using mysql_* functions anymore, and that your code is suseptible to injection.
for ($i = 0; $i < count($contactid); $i++) {
$query="INSERT INTO attendance (event_id,contact_id,group_id) VALUES ('$eventid','$contactid[$i]','$groupid')";
mysql_query($query);
}
I'm not sure running multiple queries is the best thing to do, so won't recommend making a for loop for example, that runs for each element of the array. I would rather say, make a recursive loop, that adds the new elements to a string, that then gets passed to the query. In case you can give us a short example of your DB structure and how you'd like it to look like (i.e. how the array should go into the table), I could give you an example loop syntax.
Cheers!
What about:
$contactIds = $_POST['contact_id'];
$eventIds = $_POST['event_id'];
$groupIds = $_POST['group_id'];
foreach($contactIds as $key => $value)
{
$currentContactId = $value;
$currentEventId = $eventIds[$key];
$currentGroupId = $groupIds[$key];
$query="INSERT INTO attendance (event_id,contact_id,group_id) VALUES ('$currentEventId','$currentContactId','$currentGroupId')";
mysql_query($query);
}
Well, you could refactor that to insert everything in a single query, but you got the idea.

Unknown Column in 'field list'

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.

ON DUPLICATE KEY UPDATE creating new records

I am having problems with the following code, it seems to work and creates the records just fine, the problem is each time I hit submit, instead of it updating the record it just creates a new one. If I turn off auto incremental for the primary key it updates the record just fine but then doesn't create any new ones, it seems either one or the other :-S
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('$_POST[cf_id]','$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
did you already try to echo your query string? guess the variable replacement inside it is wrong. try something like that for debugging:
<?php
$sql = "INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
('{$_POST['cf_id']}','{$_POST['cf_uid']}','{$_POST['emailformname']}','{$_POST['datesent']}')
ON DUPLICATE KEY UPDATE
datesent='{$_POST['datesent']}'";
echo $sql; // for debugging
$query = mysql_query($sql) or die(mysql_error());
?>
Note the corrected variable names above. (curly braces around it, quotes around the array index)
I can't imagine it's the problem, but does the same thing happen when you cast the ID to an int and leave out the quotes?
<?php
$query = mysql_query("
INSERT INTO hqfjt_chronoforms_data_emailform
(cf_id,cf_uid,emailformname,datesent)
VALUES
(" . (int) $_POST['cf_id'] . ",'$_POST[cf_uid]','$_POST[emailformname]','$_POST[datesent]')
ON DUPLICATE KEY UPDATE
datesent='$_POST[datesent]';
") or die(mysql_error());
?>
By the way, you really shouldn't use your $_POST variables in your query without mysql_real_escape_string or better yet, use prepared statements (PDO or mysqli).

PHP Implode not working with mysql_query

So I have two arrays, $gDatabaseKeyNames (list of column names) and $gDatabaseKeyValues (a list of variable names containing values from a script). The variable names are generated dynamically so I keep track of them for an insert.
Rather than listing all of the columns and value variables, I tried this
$cols = implode(", ", array_values($gDatabaseKeyNames));
$vals = implode(", ", array_values($gDatabaseKeyValues));
$query = "INSERT INTO pings (survey_id, $cols) VALUES ('$surveyID', $vals)";
mysql_query ($query) or die(mysql_error());
But none of my actual values show up in the database (they are inserted as 0s - all my columns are numeric).
If I echo $query, I see this, which is the correct formatting:
INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('15', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'))
However, if I change $query to
$query = INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('$surveyID', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'));
It works perfectly!
Why isn't PHP interpreting the variables in the implode? How can I fix this?
I suspect that $cols has the literal value '$Dlatitude', '$Dlongitude', etc.... PHP does not "double-interpolate" strings. It'll replace $cols with its values, but will NOT replace $Dlatitude with that variable's value. In other words, you're literally inserting some strings-that-look-like-PHP-variable-names into your numeric fields.
What is in the $gDatabaseKeyValues/Names arrays?
It's probably caused because of string/number problems. You should consider changing the database engine (Consider PDO) and use prepared statements to bind the parameters to your query the right way.

unable to insert into mysql database using php

$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 :)

Categories