Insert a PHP false into mysql - php

My MySQL table contains a tinyint(1) value that i use to store a true or false value.
I have the following PHP variables:
$name = '';
$description = '';
$active = true;
Now my SQL query is as follows:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', $active) ";
This will only work if my value for $active is true. As soon as the active variable is false, php will insert an empty string, instead of a 0 and thus the query will fail.
What is the best method to use false in such a query?
Should i manually convert the false to a '0' string?
Is it better use stings on the PHP side right away? in other words declare: $active = '1';
or can i somehow get PHP to always convert false to a '0' string?
Thanks
Michael

Convert your variable to int:
intval($active)

First of all your values should be escaped using mysql_real_escape_string or mysqli_real_escape_string or other method suitable for your database connection to avoid sql injection then for your specific question regarding false you may do something like that:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".($active?1:0) .")";
or casting $active to int should do the work too:
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('$name', '$description', ".((int) $active)).")";

use a mysql_real_escape_string function...
$query = "INSERT into my_table (my_name, my_description, active) VALUES ('".mysql_real_escape_string($name)."', '".mysql_real_escape_string($description)."', ".mysql_real_escape_string (((int) $active))).")";

Related

How to insert the same record into the database a number of times?

I have a numeric PHP variable named $quantity and based on the number set in this variable, I want to insert the same record in the MySQL table.
Example:
$quantity = '4';
$sql1 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql2 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql3 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
$sql4 = "INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());";
You can achieve this by using a loop and a prepared statement. You need to execute the same statement multiple times. This is also very useful if the values are dynamic and they could change, e.g. the values are coming from user input.
Prerequisite:
You need to open a connection to your database. If you use MySQL then the connection would look something like this:
$pdo = new PDO("mysql:host=localhost;dbname=db_name;charset=utf8mb4", 'username', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
Now you can prepare a statement which we will execute in a loop multiple times.
$stmt = $pdo->prepare("INSERT INTO table_quantity (username, code, quantity, data) VALUES ('John', '34438', '1', now());");
You can use any loop you like but for a simple scenario where we want the same code to be executed a number of times, a while loop is sufficient.
$quantity = 4;
while ($quantity--) {
$stmt->execute();
}
If it is easier for you, you can use for loop, too.
for($quantity = 0; $quantity < 4; $quantity++) {
$stmt->execute();
}
Try something like this:
// NOTICE - Make sure you are escaping any end-user supplied values correctly - See PHP docs for examples of how
$sql_template = 'INSERT INTO `table_quantity` (`username`, `code`, `quantity`, `data`) VALUES (\'John\', \'34438\', \'1\', now());';
$quantity = 5;
$sql = '';
foreach (range(1, $quantity) as $i) {
$sql .= $sql_template;
}
echo $sql;
See the following docs for explanations:
foreach
range()
append to string
Escape SQL values with PDO
Escape SQL values with MySQLi

php INSERT into column with variable name MySQL

Been looking around all over forums and found similarish issues like MySQL INSERT INTO with PHP $variable . But it's not quite getting to my question.
I want to use variables for the columns but I get errors with my MySQL insert statement
$columns = 'id, test';
$sql_store = "INSERT into test ('$columns') VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''id, Storlek') VALUES (NULL, 1)' at line 1
Thankful for help!
Problem : Your $columns variable is string which is not true.
Try like this,
PHP
$columns_array = array('id','test');
$columns = implode(",",$columns_array);
$sql_store = "INSERT into test (".$columns.") VALUES (NULL, 1)";
$sql = mysqli_query($db, $sql_store) or die(mysql_error());
It looks like your SQL command, after variable substitution, looks like
INSERT into test ('id, Storlek') VALUES (NULL, 1) /* wrong! */
It needs to say this ...
INSERT into test (id, Storlek) VALUES (NULL, 1)
or maybe this...
INSERT into test (`id`, `Storlek`) VALUES (NULL, 1)
So get rid of the quote marks surrounding your $columns variable.

Mysqli insert id returning null

$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;

MY sql query not working fully

I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.

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.

Categories