Adding data to ENUM field via form in sql - mysql

I currently have a form where values are submitted to add data to my table. I have a field 'property_id' which is an ENUM. Every time I try to submit the field I get the error message:
Fatal error: Uncaught mysqli_sql_exception: Data truncated for column 'property_id' at row 1 in ...
Is there any way I can add data to the ENUM field via my form? Here is my code below that connects the form to the database:
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$property_id = filter_input(INPUT_POST, 'property_id');
$firstline_address = filter_input(INPUT_POST, 'firstline_address');
$postcode = filter_input(INPUT_POST, 'postcode');
$vacant = filter_input(INPUT_POST, 'vacant');
if (!empty($property_id)) {
if (!empty($postcode)) {
$host = "";
$dbusername = "";
$dbpassword = "";
$dbname = "";
//new connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ')'
. mysqli_connect_error());
} else {
$sql = "INSERT INTO property (property_id, firstline_address, postcode, vacant)
values ('$property_id', '$firstline_address', '$postcode', '$vacant')";
if ($conn->query($sql)) {
echo "New property has been successfully added. Refresh page to view new property in the table below.";
} else {
echo "Error: ";
//. $sql ."<br>".$conn->error;
}
$conn->close();
}
} else {
echo "All fields are required!";
die();
}
} else {
echo "Please fill out all fields to continue.";
die();
}

Related

Find how many times every word is repeated in db

Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);

Get Btc transaction hash and send to mysql

Hello since yesterday i am trying to get the transaction hash on blockchain send many api and send to mysql but it dont works. i put to insert at mysql $txid but it give wrong results as per example "2147483647" i really thanks for any help. Below is my code.
<p>$guid="***********";
$firstpassword="**********";
$secondpassword="**************";
$amounta="3599";
$amountb="2000";
$amountc="2000";
$addressa="********";
$addressb="***********";
$addressc="******";
$recipients=urlencode('{
"'.$addressa.'": '.$amounta.',
"'.$addressb.'": '.$amountb.',
"'.$addressc.'": '.$amountc.'
}');
$json_url =
"https://blockchain.info/pt/merchant/$guid/sendmany?password=******&second_password=********&recipients=$recipients&note=********";
$json_data = file_get_contents($json_url);
$json_feed = json_decode($json_data);
$message = $json_feed->message;
$txid = $json_feed->tx_hash;
$tx = "$txid";
$servername = "localhost";
$username = "******";
$password = "*******";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$<font color="#FF0000">sql = "INSERT INTO payments (user_id, transaction_hash,
payment, date)
VALUES ('5331', '$txid', '4', now())";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;<br>
}
$conn->close();
?>
Lol, sorry that scrypt work very well, the problem i a set the table as INT 11, so i changed it to vachar 255 and its works well.
Thanks

Mysql Clone user account from database

I have a database with aproximately 200 tables. I want to clone a certain user-account in this database. Is this possible in mysql?
With cloning I mean to create a new user with the same 'settings' as the user with id 14.
A quick google search reveals that you in fact can do this. There is a utility called " "mysql user clone", that lets you surprisingly clone a user for mysql.
If you check out the manual I'm sure it provides you with great tips about how to use it, for instance, this quote:
EXAMPLES
To clone joe as sam and sally with passwords and logging in as root on the local machine, use this command:
$ mysqluserclone --source=root#localhost \
--destination=root#localhost \
joe#localhost sam:secret1#localhost sally:secret2#localhost
# Source on localhost: ... connected.
# Destination on localhost: ... connected.
# Cloning 2 users...
# Cloning joe#localhost to user sam:secret1#localhost
# Cloning joe#localhost to user sally:secret2#localhost
# ...done.
since it appears #Nanne's approach, mysqluserclone is EOL / not supported by Oracle, i wrote a similar utility in PHP, usage:
<?php
$db = new \PDO("mysql:host={$db_creds->dbhost};dbname={$db_creds->dbname};charset=utf8mb4;port=" . $db_creds->dbport, $db_creds->superuser_user, $db_creds->superuser_pass, array(
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
));
Mysqluserclone::clone_account($db, "original username", "cloned username");
and this part of the code may be of particular interest:
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
<?php
class Mysqluserclone{
private function __construct(){
// by making this private, we ensure nobody try to instantiate us.
}
public static function clone_account(\PDO $db_connected_as_superuser, string $original_name, string $clone_name): void
{
$db = $db_connected_as_superuser;
$sqls_for_cloning = [];
$sql = "SELECT COUNT(*) FROM mysql.user WHERE User = " . $db->quote($clone_name);
if (0 !== $db->query($sql)->fetch(\PDO::FETCH_NUM)[0]) {
throw new \InvalidArgumentException("clone name already exists!");
}
$sql = "SELECT * FROM mysql.user WHERE User = " . $db->quote($original_name);
$current_user_one_for_each_host = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
foreach ($current_user_one_for_each_host as $user_record) {
$user_record["User"] = $clone_name;
$sql = "INSERT INTO mysql.user SET \n";
foreach ($user_record as $name => $val) {
$sql .= self::mysql_quote_identifier($name) . " = " . self::mysql_quote_better($db, $val) . ",\n";
}
if (! empty($user_record)) {
$sql = substr($sql, 0, - strlen(",\n"));
}
$sql .= ";";
$sqls_for_cloning[] = $sql;
$sqls_for_cloning[] = "FLUSH PRIVILEGES;"; // YES this is required, otherwise you might get "grant not allowed to create accounts" errors
$grants_raw_sql = 'SHOW GRANTS FOR ' . $db->quote($original_name) . '#' . $db->quote($user_record['Host']) . ";";
try {
$grants_raw = $db->query($grants_raw_sql)->fetchAll(\PDO::FETCH_NUM);
} catch (\Throwable $ex) {
// somehow an empty grant table is a mysql error, not an empty rowset.. ignore it.
$grants_raw = [];
}
$grants_raw = array_map(function (array $arr): string {
if (count($arr) !== 1) {
throw new \LogicException("mysql layout for SHOW GRANTS has changed? investigate");
}
return $arr[0];
}, $grants_raw);
$original_name_as_identifier = self::mysql_quote_identifier($original_name);
$clone_name_as_identifier = self::mysql_quote_identifier($clone_name);
foreach ($grants_raw as $grant) {
if (false === strpos($grant, $original_name_as_identifier)) {
throw new \LogicException("original grant without original name as identifier? investigate");
}
$grant = self::str_replace_last($original_name_as_identifier, $clone_name_as_identifier, $grant);
$grant .= ";";
$sqls_for_cloning[] = $grant;
}
}
if (! empty($sqls_for_cloning)) {
$sqls_for_cloning[] = "FLUSH PRIVILEGES;";
}
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
foreach ($sqls_for_cloning as $clone_sql) {
$db->exec($clone_sql);
}
}
private static function mysql_quote_identifier(string $identifier): string
{
return '`' . strtr($identifier, [
'`' => '``'
]) . '`';
}
private static function mysql_quote_better(\PDO $db, $value): string
{
if (is_null($value)) {
return "NULL";
}
if (is_int($value)) {
return (string) $value;
}
if (is_float($value)) {
return number_format($value, 10, '.', '');
}
if (is_bool($value)) {
return ($value ? "1" : "0");
}
return $db->quote($value);
}
private static function str_replace_last(string $search, string $replace, string $subject): string
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
}

MySQL Updating database error

Im trying to get it so when you press a button it updates the value of 'subscribe' to 1 but for some reason its not working.
<?php
session_start();
$userid = $_SESSION['userID'];
$username = $_SESSION['username'];
require '../../core/connect.php';
if ($_SESSION['userID']) {
if (isset($_POST['subscribe'])) {
$query2 = mysql_query("UPDATE `users` SET `subscribe`='1' WHERE `username`='".$username."'") or die(mysql_error());
if ($query2) {
header("Location: /index.php");
} else {
echo "An error occured. Your subscription failed! Please try again later.";
}
}else {
echo "Error occured.";
}
}else {
echo "No session found.";
}
?>
The error im getting is the 'Error occured.'
The field is an int with the default value as 0
Thanks!
'Error Occurred' implies
if(isset($_POST['subscribe'])) // is evaluating to false
use
print_r($_POST) // and post the result
if(isset($_SESSION['subscribe']))

Live Search With Mysql and PHP

I am building a Live Search function on my website, I used the W3schools example, which worked perfectly. But I want to use MySQL database instead of the XML file, so I am working on a code to take the MySQL database and turn it into an XML file.
<?php
header("Content-type: text/xml");
include 'dbc.php';
$query = "SELECT * FROM airports";
$result = mysql_query($query, $link)
or die('Error querying database.');
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<entries>\n";
for($x = 0 ; $x < mysql_num_rows($result) ; $x++){
$row = mysql_fetch_assoc($result);
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<ident>" . $row['ident'] . "</ident>\n";
// Escaping illegal characters
$row['name'] = str_replace("&", "&", $row['name']);
$row['name'] = str_replace("<", "<", $row['name']);
$row['name'] = str_replace(">", ">", $row['name']);
$row['name'] = str_replace("\"", """, $row['name']);
$xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
?>
I am getting this error:
Warning: DOMDocument::load() [domdocument.load]: Start tag expected, '<' not found in /public_html/sql2xml.php, line: 11 in /public_html/livesearch.php on line 12
no suggestion
I have read the explanation at: Avoid DOMDocument XML warnings in php
But I have no idea how to fix that in my code. Any suggestions?
This will take the data from the 'Name' column in your mysql table and put it into an array its the same array w3c school looks up as you type
$mysqli = new mysqli(HOST,USER,PASSWORD,DATABASE);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{
$a[]=$row["Name"];
}
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
if (isset($q))
{
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
}