I tried for long time understand what got wrong in this code:
I have two arrays that I want to put in the DB but the array can be changed any time. So it need to work dynamically.
All I get is an empty row without any data - but as string it work fine.
If I write the output string of query instead it works, but this way not:
$fields = $values = array();
$j = 0;
while ($j < mysql_num_fields($query)) {
$namee = mysql_fetch_field($query, $j)->name;
if(isset($AutoFill[$namee])){
if($AutoFill[$namee] == '?')
$values[] = "'".mysql_real_escape_string("dopd")."'";//$_POST[$namee]
else
$values[] = "'".mysql_real_escape_string($AutoFill[$namee])."'";
$fields[] = "$namee";
}
$j++;
}
$fields = implode(",", $fields);
$values = implode(",", $values);
// not working
mysql_query("INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")");
// "INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")" => tostring working:
mysql_query("INSERT INTO _users (user_name,display_name,password,email,activation_token,last_activation_request,lost_password_request,active,title,sign_up_stamp,last_sign_in_stamp) VALUES ('dopd','dopd','dopd','dopd','dopd','1409863484','0','dopd','New Member','1409863484','0')");
This will not work because you cannot pass an array into a query.
mysql_query("INSERT INTO ".$table_name." (".$fields.") VALUES (".$values.")");
Try this instead:
mysql_query( "INSERT INTO ".$table_name." ('" . implode("','", $fields) . "') VALUES ('" . implode("','", $values) . "');" );
This will create a string out of your array that will pass into the SQL statement correctly. Do your implode within the query statement rather than above. Also, you were not wrapping the values in quotes individually, so you were getting one long string of values (ie: '1,2,3') instead of individually quoted values (ie: '1','2','3').
The solution for this was that the $query was not declered properly in the right place og scope.
The code work's great on any king and length of information from user.
thank you all - best weekend.
Related
I am in a confusion.
I have a cron job written in PHP to insert values into a table. But some values may already exist in the table. But we are not sure which are they. So I used INSERT IGNORE INTO method to insert my entries like follows,
$insertSql = "INSERT IGNORE INTO `my_procuts` (`product_id`, `category_id`) VALUES " . $valueString . ";";
$insertResult = mysqli_query($conn, $insertSql);
$affectedRows = mysqli_affected_rows($conn);
Where $valueString is the output of a previous for loop. And those are the values to insert. This query works fine. Values are inserting as I expected.
Now,
I want to add a TRANSACTION to this insertion. So I try it like this,
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_ONLY);
$insertSql = "INSERT IGNORE INTO `my_procuts` (`product_id`, `category_id`) VALUES " . $valueString . ";";
$insertResult = mysqli_query($conn, $insertSql);
$affectedRows = mysqli_affected_rows($conn);
mysqli_commit($conn);
Now the query is not working. $affectedRows gives -1 result always. What may the issue I have made.
Thanks in advance. :)
i have json as input
$page = file_get_contents('http://example.com/products.html');
$items = json_decode($page, true);
if i put echo $page; i get smth like this
{
"productlist":[
{
"id":"1",
"cat":"milk",
"prod_name":"happy milk",
"img_url":"http://example.com/milk.jpg"},
{
"id":"2",
"cat":"bread",
"prod_name":"black bread",
"img_url":"http://example.com/bread.jpg"},
then, i want to put it into MySQL DB
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = $item['cat'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
at this stage i get nothing. if i modify code into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id) VALUES ($id)") or die(mysql_error());
}
i get the table in DB filled - i have two rows with prod id. Ok, i want to insert into table the $cat = food
foreach($items['productlist'] as $item) {
$id = $item['id'];
$cat = 'food';
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, $cat)") or die(mysql_error());
}
yet this does not work, i get null result. but if i modify query into
foreach($items['productlist'] as $item) {
$id = $item['id'];
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, 'food')") or die(mysql_error());
}
i get the result i seek for - tho rows in table, filled with id and cat
id cat
1 food
2 food
does anyone know how to send string value into insert query via variable?
That doesn't work because cat is a String field, need to be between quotes '...'. try this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
or this :
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".$cat.")") or die(mysql_error());
First, I would suggest you to learn how to use prepared statements, as you are getting your strings outside of your code (it may contain some mysql injections).
To answer your question, you need to put some quotes around the variable you want to put in your query as it is a string, so mysql can interpret it correctly
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, '$cat')") or die(mysql_error());
Try this
mysqli_query($link, "INSERT INTO table (id, cat) VALUES ($id, ".mysql_real_escape_string($cat).")") or die(mysql_error());
I've got a portion of code that is supposed to take the data entered in a form, store it in an array and then enter it into the database. I have used var_dump on $fields and $data and they are both returning the information entered in the field (in the add_habbo function). So the problem I've got is that the MYSQL/PDO code isn't inserting this data into the database.
This is the code that I am using to insert them into the database:
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$data = '\'' . implode('\', \'', $habbo_data) . '\'';
var_dump($fields);
var_dump($data);
global $con;
$query = "INSERT INTO `personnel` (:fields) VALUES (:data)";
$result = $con->prepare($query);
$result->bindParam(':fields', $fields, PDO::PARAM_STR);
$result->bindParam(':data', $data, PDO::PARAM_STR);
$result->execute();
I get the impression it has something to with the bindParam sections, possibly PDO::PARAM_STR? Thanks for your assistance!
Update:
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$fields_data = ':' . implode(', :', array_keys($habbo_data));
var_dump($fields);
var_dump($fields_data);
global $con;
$query = "INSERT INTO `personnel` (`rank`, `habbo_name`, `rating`, `asts`, `promotion_date`, `transfer_rank_received`, `cnl_trainings`, `rdc_grade`,
`medals`, `branch`) VALUES ({$fields_data})";
$result = $con->prepare($query);
$result->execute($habbo_data);
$arr = $result->errorInfo();
print_r($arr);
Error:
Array ( [0] => 21S01 [1] => 1136 [2] => Column count doesn't match
value count at row 1 )
Prepared statements are not the same as copy and paste!
INSERT INTO `personnel` (:fields) VALUES (:data)
You're telling PDO/MySQL here that you want to insert exactly one piece of data (:data) into one field (:field). The value is one string containing commas, not several values separated by commas.
Furthermore you can only bind data, not structural information like field names. You will have to create a query like so:
INSERT INTO `personnel` (foo, bar, baz) VALUES (?, ?, ?)
and then bind data to the three placeholders separately.
You cannot do that:
You need to add each variable / field-name and value individually;
You can only bind values and not table- or field-names.
Table- and field-names you will have to inject directly into your sql so to prevent sql injection problems, you need to check them against a white-list before doing that.
So in your case that would be something like (rough draft):
// assuming all fields have been checked against a whitelist
// also assuming that the array keys of `$habbo_data` do not contain funny stuff like spaces, etc.
$fields = '`' . implode('`, `', array_keys($habbo_data)) . '`';
$fields_data = ':' . implode(', :', array_keys($habbo_data));
var_dump($fields);
var_dump($fields_data);
global $con;
$query = "INSERT INTO `personnel` ({$fields}) VALUES ({$fields_data})";
$result = $con->prepare($query);
$result->execute($habbo_data);
Note that I am not manually binding the variables any more but sending the associative $habbo_data array directly as a parameter to the execute method, see example #2.
I am trying to insert multiple rows based on a loop.
This code inserts the first item from the loop only, then ignores the rest of the loop
I know the loop is counting correctly as echo'ing out the values outputs ok
$i = 1;
while ($i <= $count){
foreach($html->find('.markuptag a') as $mystring){
if(preg_match_all("|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i", $mystring, $matches)){
$a = $matches[2][0];
}
$query = "INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES ('$fistname', '$lastname', '$a')";
$mysqli->query($query);//<< is there a better way?
}
$i++;
}
Build an array of the rows to insert, then insert them all at once. Something like this:
$arr = []; // array() in PHP 5.3 and older
foreach(...) {
...
$arr[] = "('$fistname', '$lastname', '$a')";
}
$mysqli->query("INSERT INTO mytable (`firstname`, `lastname`, `var_a`) VALUES "
.implode(",",$arr));
I'm having a little trouble with my insert statement this morning. Yes, I am using the deprecated mysql_query function. My insert statement looks as follows:
$query3 = "INSERT INTO ".$db_prefix ." offer_det
(fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
VALUES '".$fname."', '".$lname."', '".$_10k."', '".$_14k."',
'".$_18k."', '".$_21k."', '".$_22k."', '".$_24k."',
'".$_925."', '".$coins."', '".$bars."')";
$result3 = mysql_query($query3);
My PHP form values are all the variables listed in the first part of the insert statement, 'fname', etc.
My variables are set to pull from the post and are listed as the values going into the insert.
I had to change the variables to underscore before they started, I guess PHP didn't like that.
My questions:
Are those 10k, 14k, etc, okay mysql table row names?
Is there an issue I'm missing here?
The datatype for fname and lname are varchar and for the 10k through bars are decimal (7,3).
The column name 925 must be quoted using backticks.
(`fname`, `lname`, `10k`, `14k`, `18k`, `21k`, `22k`, `24k`, `925`, `coins`, `bars`)
You may also want to consider changing the column names to something else to avoid further similar problems in the future.
You should quote the 925 column name, as per MySQL Schema Object names
So correctly:
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, `925`, coins, bars)
values
('".$fname."', '".$lname."', '".$_10k."', '".$_14k."', '".$_18k."', '".$_21k."',
'".$_22k."','".$_24k."', '".$_925."', '".$coins."', '".$bars."')";
Another recommendation: you should escape the incoming strings, because SQL injection is a nasty thing to experience...
Use the QUERY as like follow..
$query3 = "insert into ".$db_prefix."offer_det (fname, lname, 10k, 14k, 18k, 21k, 22k, 24k, 925, coins, bars)
values ('$fname', '$lname', '$_10k', '$_14k', '$_18k', '$_21k', '$_22k',
'$_24k', '$_925', '$coins', '$bars')";
$query_exec=mysql_query($query3) or die(mysql_error());
And for inserting a variable you need to use single codes only..
Can I be bold and suggest a change in your implementation?
/// put your vars in an easier to use format
$insert = array(
'fname' => $fname,
'lname' => $lname,
'10k' => $_10k,
/* and so on ...*/
);
/// considering you are using mysql_query, use it's escape function
foreach ( $insert as $field => $value ) {
$insert[$field] = mysql_real_escape_string($value);
}
/// pull out the keys as fields and the values as values
$keys = array_keys($insert);
$vals = array_values($insert);
/// the following should auto backtick everything... however it should be
/// noted all the values will be treated like strings as you were doing anyway
$query = "INSERT INTO `" . $db_prefix . "offer_det` " .
"(`" . implode('`,`', $keys) . "`) " .
"VALUES ('" . implode("','", $vals ) . "')";