MySQL Insert from PHP - php

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 ) . "')";

Related

Error in insert into statement MySQL PHP

I am having error and I am not able to identify the problem. I will really appreciate help.
$sql = "INSERT INTO scrapeddata (Id,Store, ImageURL, ShortDescription, CashPercentage, ShoppingPoints, LongDescription, Contact, Information)
VALUES ($ID, $name, $ImageUrl, $ShortDecription, $CashBack, $SallingPoints, $LongtDecription, $Contact, $Information)";
Structure of my Table is :
Update :
Following image illustrate the actual error, php variable is resolved dynamically to retreive the string , but "with in the string" it contains single quotes ' according to me these quotes are causing error . Help !!
Put quotations on string variables.
And escape all ur variables before inserting in query.
mysql-escape-string
$name = mysql_escape_string($name);
$sql = "INSERT INTO scrapeddata (Id,Store, ImageURL, ShortDescription, CashPercentage, ShoppingPoints, LongDescription, Contact, Information)
VALUES ('$ID', '$name', '$ImageUrl', '$ShortDecription', '$CashBack', '$SallingPoints', '$LongtDecription', '$Contact', '$Information')";

Not inserting data to database from link

So when someone press this link, it should insert all the data from that text id to a new table but with the username who clicked it and the id of the text the user pressed.
The problem is, when a user clicks the link, it doesn't insert the data, what could be wrong?
The session works, so it must be something with the GET?
<?php
if(isset($_GET['collect'])) {
$perman = $_GET['collect'];
$username = $_SESSION['username'];
$query = $dbh->query("INSERT INTO collections (id, ad, user) VALUES ('', $perman, $username)");
echo 'Saving';
echo $perman;
header ('Refresh: 1; URL=http://localhost/de/collect.php');
}
?>
First, inserting '' for ID isn't very good (don't know if it works), don't use it (uses default), or insert NULL (uses default too, if NOT NULL).
Second, to insert values it's good practice to enquote it and use escape_string on it. I think that's your problem.
$query = $dbh->query("INSERT INTO collections (ad, user) VALUES ('" . $dbh->escape_string($perman) . "', '" . $dbh->escape_string($username) . "')");
You should be doing it like this...if you're using PDO
Much safer, with prepared statements
$sql = "INSERT INTO books (id,ad,user) VALUES (:id,:ad,:user)";
$q = $conn->prepare($sql);
$q->execute(array(':id'=>null,':ad'=>$perman,':user'=>$username));
You tagged your Question with "PDO". Are you using PDO? If yes, why are you not using bindParam() or bindValue()?
If $perman and $username are strings, you've to escape them:
$query = $dbh->query("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES ('', '{$perman}', '{$username}')");
That query should work, but there are still security issues. You've to escape the values. With PDO it's very simple.
General: use http://php.net/manual/en/function.mysql-error.php
Your column "id" should be Integer and have an auto_increment. Of course some IDs are Strings, but if you're able to avoid it, avoid it!
You could print out the $_GET params by using
print_r($_GET);
Edit
Example with PDOStatement::bindValue():
$stmt = $dbh->prepare("INSERT INTO `collections` (`id`, `ad`, `user`) VALUES (:id, :ad, :user)");
$stmt->bindValue(":id", 123);
$stmt->bindValue(":ad", "ad");
$stmt->bindValue(":user", "username");
$stmt->execute();

Multiply an insert in database from php

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) . "');"

PHP not getting parameters

I acces my page passing some parameters through the URL:
www.mypage.com/page.php?aID=4091cdcd-773d-4ca5-bab2-41e1188870a9&sID=1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-&nam=Gab&tel=7777777777
then in my PHP code I have:
if(isset($_GET['sID'])) {
$sID = $_GET['sID'];
}
if(isset($_GET['aID'])) {
$aID = $_GET['aID'];
}
if(isset($_GET['nam'])) {
$nam = $_GET['nam'];
}
if(isset($_GET['tel'])) {
$tel = $_GET['tel'];
}
I have no problem retrieving $nam and $tel, but $aID and $sID always get an empty string. I have tried using double quotes (isset($_GET["aID"])) , but it has not made any difference.
Are there illegal characters on the string or a limit in size of a variable you can pass through the URL? How can I GET variables $aID and $sID?
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
echo $query;
Echo $query's output is:
INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('', '', 'Gab', '7777777777' )
Testing your URL, I get the following result:
Array
(
[aID] => 4091cdcd-773d-4ca5-bab2-41e1188870a9
[sID] => 1_MX4yMjI1MTgxMn4xMjcuMC4wLjF-V2VkIERlYyAyNiAwOTo1MDoyNiBQU1QgMjAxMn4wLjg1MjA4MTF-
[nam] => Gab
[tel] => 7777777777
)
Therefore, I'm not sure what you mean by you're getting an empty string. You did have a typo in your code, where $tel references $_GET['aID']. I would advise you verify your code.
I would recommend that you also use $_SERVER['REQUEST_METHOD'] to verify that your script is using GET.
Update
Per your updated query, it seems as though your case is incorrect. The variable name is case-sensitive.
$query = "INSERT INTO ... VALUES ('$aiD', '$siD', '$nam', '$tel' )";
^ ^
Should be:
$query = "INSERT INTO ... VALUES ('$aID', '$sID', '$nam', '$tel' )";
You have to enable error reporting and logging to the highest level when you develop PHP.
You have to check return values of methods you call to see if they did what you thought they did. You have to look for more error information if something failed.
You have to look into prepared statements to prevent SQL injection.
And yes, mysql_* functions are deprecated. Do not use it for new code.
You notice in your sql statement you are not calling the variables you defined:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aiD', '$siD', '$nam', '$tel' )";
should be:
$query = "INSERT INTO myTable (ArchiveID, SessionID, Name, Tel) VALUES ('$aID', '$sID', '$nam', '$tel' )";
and looks like njk updated his answer to reflect this so he should be credited for the answer.

MySQL error: "Column count doesn't match value count at row 1" - beginner help

basically, php & MySQL being used. I am a beginner.
What I am trying to do is registering a user to my database, so storing the form input to my users_tb.
get this error when I try inserting the values into the form:
"Column count doesn't match value count at row 1"
I thought it was because I wasn't inserting the user_id value (which is auto increment), so I tried inserting '' in my query for the user_id, but still no luck.
here is the query:
$query = "INSERT INTO users_tb (user_id, user_status, user_gender, user_firstname, user_surname, student_number,
user_email, user_dob, user_name, user_pass)
VALUES('','$status','$gender','$firstname','$surname','$hnumber','$dob','$username','$password')";
mysql_query($query) or die(mysql_error());
mysql_close();
whether that helps. If you need any other code just say.
just to make sure though, the inserts don't have to be in same order the fields are in the table do they?
many thanks,
You're missing one value.
For queries this long with so many columns (and if you're inserting just one row), I'd suggest using the following INSERT syntax, which is much easier to read and less likely to cause problems.
$query = "INSERT INTO users_tb SET
user_status = '". mysql_real_escape_string($status) ."',
user_gender = '". mysql_real_escape_string($gender) ."',
user_firstname = '". mysql_real_escape_string($firstname) ."',
user_surname = '". mysql_real_escape_string($surname) ."',
student_number = '". mysql_real_escape_string($hnumber) ."',
user_email = '". mysql_real_escape_string($email) ."',
user_dob = '". mysql_real_escape_string($dob) ."',
user_name = '". mysql_real_escape_string($username) ."',
user_pass = '". mysql_real_escape_string($password) ."'";
mysql_query($query) or die(mysql_error());
mysql_close();
You are missing a value for user_email.
$query = "INSERT INTO users_tb
(
user_status,
user_gender,
user_firstname,
user_surname,
student_number,
user_email,
user_dob,
user_name,
user_pass
)
VALUES
(
'$status',
'$gender',
'$firstname',
'$surname',
'$hnumber',
'$email', -- <--- you forgot this!
'$dob',
'$username',
'$password'
)";
And just a reminder: you should escape the values using mysql_real_escape_string if you are not already doing so.
Mark Byers answered the problem part, but didn't address this question:
just to make sure though, the inserts don't have to be in same order the fields are in the table do they?
No, they don't have to be in the same order as the columns in the table, but your columns list and your values list have to match both in count and in data type. The problem you have is the one Mark spotted; you're missing a value for user_email, which means the dob value is trying to go in that column instead. MySQL is seeing that there aren't enough values for the columns you listed, and reporting the error back to you.
Column count doesn't match value count is actually a pretty clear message, which is unusual for database engines. :)
You can use this simple function to create a query out of $_POST array and list of allowed fields:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
used like this
$table = "users_tb";
$fields = explode(" ","user_status user_gender user_firstname user_surname student_number user_email user_dob user_name user_pass");
$query = "INSERT INTO $table SET ".dbSet($fields);
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
of course it's assuming that HTML form field names match SQL table field names, which is very handy consideration
you've got 10 fields you want to insert, but you're providing only 9 values
You list 10 columns but you only have 9 values.

Categories