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. :)
Related
I understand that such questions have been downvoted or closed, however I've been through all the previously asked questions and couldn't find any solutions. The code is supposed to accept input from a HTML form and insert it into the MySQL database and be displayed on another page, but somehow I end up with query failed statement and redirected to the Login page.
<?php
if (isset($_POST['eTransport_ID'])){
$id = ($_POST['eTransport_ID']);
}
if (isset($_POST['Phone_No'])){
$phone = ($_POST['Phone_No']);
}
if (isset($_POST['Amount'])){
$amount = ($_POST['Amount']);
}
$DATEE = date("Y-m-d");
$TIMEE = date("h:i:sa");
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ('$DATEE', '$TIMEE', '$amount', 'WEB', '$id')";
$added = mysqli_query($conn, $query);
if(!$added){
die("Database query failed.");
}
else{
echo "Data Entered Successfully";
}
mysqli_close($conn);
?>
MySQL Table
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ('$DATEE', '$TIMEE', '$amount', 'WEB', '$id')";
Can you write query like this
$query = "INSERT INTO recharge_history(Date, Time, Amount, Agent_No, eTransport_ID) VALUES ($DATEE, $TIMEE, $amount, $phone, $id)";
This is BAD code which has severe SQL injection vulnerabilities so please look into that separately (your question isn't about security)
I'm assuming 'Date' is a DATE column
I'm assuming 'Time' is a TIME column
It looks as though Agent_No may be an INT column, but you're inserting a string. I've substituted for a "1" so you'll have to look at that separately.
If my assumptions are correct, just change the query line to exactly this (ie: copy and paste it):
$query = "INSERT INTO recharge_history (`Date`, `Time`, `Amount`, `Agent_No`, `eTransport_ID`) VALUES (NOW(), NOW(), $amount, 'WEB', $id)";
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.
$S = "INSERT INTO ". TBD ." (NODE, AV, BV) VALUES ('15', '$name', '$email')";
$Q = $CONN->query($S);
$M = $Q->insert_id;
$M returns NULL not 0
The above script runs the query fine, but will not return the unique ID generated.
The table, definitely has a auto increment and is a primary key.
I have used the script elsewhere and works fine.
So I have no idea why its returning NULL now.
I think you are calling insert_id wrong. Try this:
$S = "INSERT INTO ". TBD ." (NODE, AV, BV) VALUES ('15', '$name', '$email')";
$Q = $CONN->query($S);
$M = $CONN->insert_id;
You need to extract the insert_id from the connection object and not the result set.
Your $Q variable is a mysqli result object so you'll want to extract the inserted id like this:
$CONN->insert_id;
I have a php that inserts a number to my database. I would like that every value of 1 should be 0,01 in the database so if a person enters 50 it will be inserted as 0,5 in the database. This means i have to multiply the number from the php with 0,01. Is this possible? I have this code which insert the number to the database $sql = "insert into $DB_Table (score) values('$points');";
First of all you should probably look into mysqli, which will grant you safer interaction with mysql.
You could solve your problem like this though:
$sql = sprintf("INSERT INTO %s (score) VALUES ('%s');", $DB_Table, $points * 0,01);
In mysqli the corresponding would be something like:
$stmt = $db->prepare("INSERT INTO $DB_Table (score) VALUES (?);");
$stmt->bind_param("s", $point * 0,01);
$stmt->execute();
This helps you avoid SQL injection and the such.
Good luck with your project.
$sql = "INSERT INTO $DB_Table (`score`) VALUES('" . ($points*0.01) ."');";
have you tried
$sql = "insert into $DB_Table (score) values('".($points / 100)."');";
Also you don't mention what datatype your field is; I believe decimal is what you need, not int
$sql = "insert into $DB_Table (score) values('" . ($points / 100) . "');"
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 ) . "')";