multi_query not working when creating registers on tables - mysqli

The thing is that I'm trying to create multiple tables with multi_query and right after two registers in two of those tables. When I run the code the tables are created in the DB but the registers cannot be created. Te thing is that when I do everything with a simple query then the code works perfectly. I don't know what I'm missing here... here is the code:
if (isset($_POST['usercp']) && !empty($_POST['usercp'])) {
if (isset($_POST['passlogin']) && !empty($_POST['passlogin'])) {
$conn = mysqli_connect($host, $user, $pw, $db);
if (!$conn) {
echo "<script language='javascript'>alert('Usuario de CPanel incorrecto!!');window.location.href = 'http://here-a-page.com/';</script>";
}
else {
$sql = "CREATE TABLE usercp (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
usuario VARCHAR(30) NOT NULL
);";
$sql = $sql . "CREATE TABLE numlink (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Link VARCHAR(30) NOT NULL
);";
$sql = $sql . "CREATE TABLE login (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
Validacion_Pass VARCHAR(30) NOT NULL
);";
$file = fopen("UsuarioCpanel.txt", "w");
fwrite($file, $UserCp . PHP_EOL);
fclose($file);
if ($conn->multi_query($sql)) {
$PassLogin = $_POST['passlogin'];
$consulta = " INSERT INTO usercp(usuario) VALUES('$UserCp');";
$consulta = $consulta . "INSERT INTO login(Validacion_Pass) VALUES('$PassLogin');";
if ($conn->multi_query($consulta)) {
header('location: index.php');
}
else{
echo "Ocurrio un error creando los registros";
}
}
else{
echo "Error creating table: " . $conn->error;
}
}
}
else{
echo "<script language='javascript'>alert('Debes poner el Password que utilizaras con el Login del Cloaking System');window.location.href = 'http://here-a-page.com/';</script>";
}
}
else {
echo "<script language='javascript'>alert('Debes poner tu Usuario de CPanel');window.location.href = 'http://here-a-page.com/';</script>";
}
I've found a solution to my problem in a question similar to mine. #furas solved this problem with a "while(){}" after every multi_query you want to do. For some reason multi_query can't be run more than once naturally. To do that you need to write this lines after every multi_query:
while( mysqli_more_results($link) ){
$result = mysqli_store_result($link);
mysqli_next_result($link);
}

I've found a solution to my problem in a question similar to mine. #furas solved this problem with a "while(){}" after every multi_query you want to do. For some reason multi_query can't be run more than once naturally. To do that you need to write this lines after every multi_query:
while( mysqli_more_results($link) ){
$result = mysqli_store_result($link);
mysqli_next_result($link);
}

Related

Geocoding mysql addresses

I want to geocode mysql addresses to get latitude and longitude and save them into mysql table. I got this code from a friend some time ago, so somenthing could be deprecated.
I have this scripts:
index.php
<!DOCTYPE html PUBLIC "-//W§C/DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Geocodification</title>title>
<?php
require("config.php");
$output = '';
$markerListLat = array();
$markerListLng = array();
$connection = mysql_connect('localhost', BBDD_USER, BBDD_PASSWD);
if (!connection) { die("Error en la connecion a la BBDD: " . mysql_error()); }
$db_selected = mysql_selected_db(BBDD_NAME, $connection);
if (!$db_selected) { die("Error en el accesso al BBDD: " . mysql_error()); }
$query = 'SELECT * FROM tplace WHERE 1 ORDER BY id ASC';
$result = mysql_query($query);
if (!result) { die("Error en la consulta a la BBDD: " . mysql_error()); }
$delay = 0;
$base_url = "http://".MAPS_HOST."/maps/geo?output=csv&key=".KEY;
$output = '<dl>';
while ($row = #mysql_fetch_assoc($result))
{
$geocode_pending = true;
while ($geocode_pending)
{
$id = $row["id"];
$address = utf8_decode($row['direccion']).', '.utf8_decode($row['codigo_postal']);
$request_url = $base_url."&q=".urlencode($address);
$csv = file_get_contents($request_url) or die("url not loading");
$csvLine = explode(",", $csv);
$status = $csvLine[0];
$lat = $csvLine[2];
$lng = $csvLine[3];
array_push($markerListLat, $lat);
array_push($markerListLng, $lng);
if (strcmp($status, STATUS_OK) == 0)
{
// EXITO EN LA GEOCODIFICATION
$geocode_pending = false;
//Actualizamos los valores de la BBDD
$query = sprintf("UPDATE tplace = " .
" SET latitud = '§s', longitud = '§s' " .
" WHERE id = §s LIMIZ 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
if (!$update_result)
{
die ("SQL Query erronea: " . mysql_error());
}
else
{
$output .= '<dt>EXITO > geocodificando la siguiente direccion: '.$address.'</dt>';
$output .= '<dd>(Lat, Lng) > ('.$lat.', '.$lng.')</dd>';
}
usleep($delay);
}
}
$output .= '</dl>';
?>
</head>
<body onload="initialize();">
<h1>Geodification de Base de Datos</h1>h1>
<p><?php echo $output; ?></p>
</body>
</html>
config.php
<?php
define('BBDD_USER', 'root');
define('BBDD_PASSWD', '');
define('BBDD_NAME', 'geocoding_demo');
define('MAPS_HOST', 'maps.google_demo');
define('KEY', 'MY KEY');
define('STATUS_OK', '200');
define('STATUS_KO_TIME', '620');
define('DELAY_TIME', 1000000);
define('SPAIN_LAT', 40.396764);
define('SPAIN_LNG', -3.713379);
define('SPAIN_ZOOM', 6);
?>
tplace.sql
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Database: `geocoding_demo`
--
-- --------------------------------------------------------
--
-- Table structure for table `tplace`
--
CREATE TABLE `tplace` (
`id` int(11) NOT NULL,
`nombre` varchar(100) NOT NULL,
`direccion` varchar(100) NOT NULL,
`localidad` varchar(100) NOT NULL,
`codigo_postal` varchar(100) NOT NULL,
`pais` varchar(100) NOT NULL,
`latitud` float(10,6) NOT NULL,
`longitud` float(10,6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tplace`
--
INSERT INTO `tplace` (`id`, `nombre`, `direccion`, `localidad`, `codigo_postal`, `pais`, `latitud`, `longitud`) VALUES
(1, '', '68 Rue Jean Jaurès, 'Bauvin', '59221', 'Frankreich', 0.000000, 0.000000),
(2, '', 'via castello, 19', 'Bargni', '61030', 'Italien', 0.000000, 0.000000),
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tplace`
--
ALTER TABLE `tplace`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tplace`
--
ALTER TABLE `tplace`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
I am getting blank page on browser and this error: GET HTTP/1.0 500 Internal Server Error.
Does someone could please help me?
Thanks,
Nicola

mysqli int update syntax error

Im trying to update a field on my database but keep getting the message that my sqli code has a syntax error. I am unable to find that error, i prevously has On and Id in all caps but changed it incase it was reserved by mysqli (db.php just has my database details)
include ("db.php") ;
// connect to the database to get current state
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) { die("Connection failed: " . mysqli_connect_error());
echo "fail"; }
Also tried it as "On = 1"
$sql = "UPDATE GreenLED SET On='1' WHERE Id=1";
$result = mysqli_query($conn, $sql);
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
"On" aswell as "ON" are reserved by sql and so i had to change On to LOn

Mysqli not inserting data on table

Here's my code:
// Register User
$sql = "INSERT INTO users (username, password, email, register_date)
VALUES ('$username', '$md5pass', '$email', '$date')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$sql = "INSERT INTO skills (user_id)
VALUES ('$last_id')" or die(mysqli_error($conn));
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Well the first table is created and everything seems ok but the second table (skills) it's not being inserted.
Can anyone tell what I'm doing wrong?
You create the second insert query, but you are not executing it.
Also, you should be checking the result of mysqli_insert_id, in case this call fails.

Codeigniter 3 get a specific session data by id

Codeigniter 3 session table looks like the following
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(40) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
I can access my current session by
$this->session
But If I'd like to access a specific session how would I do that.
I can get the session like
$this->db->where('id', 'db256c0b82f8b6ba1e857d807ea613792817157a');
$res = $this->db->get('ci_sessions');
echo $res->row()->data;
I get the following
__ci_last_regenerate|i:1450694483;email|s:18:"amzadfof#gmail.com";user_code|s:7:"AAA1787";loginInId|i:8;users_id|s:11:"00000000002";active|s:1:"1";username|s:13:"amzadmojumder";fname|s:5:"Amzad";lname|s:8:"Mojumder";phone|s:11:"07900642131";title|s:1:"#";created_on|s:19:"2015-12-17 16:31:56";last_login|s:19:"0000-00-00 00:00:00";in_group|s:15:"2,1,3,4,5,6,7,8";
How could I convert this to an php object or array? I have tried to
unserialize($res->row()->data);
Also tried
session_decode($res->row()->data);
none of this worked. Any help will be appreciated.
Old question, yeah but this worked for me.
https://github.com/wikimedia/php-session-serializer
After fetching the session data from database, I just did
$array = PhpSessionSerializer::decode($session);
Firstly, the CodeIgniter sessions table should look a bit more like this:
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(45) DEFAULT '0' NOT NULL,
user_agent varchar(120) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
user_data text NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);
You'll also need to edit your config.php to ensure the following are set properly for CI Sessions to use a table for storage
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
The other issue you'll face is that you aren't really using sessions how they're supposed to be used. If you want to mimic sessions of another individual through an admin switch or something like that, you're probably best off creating a new session and duplicating the information in your table. If you actually assume the session, you risk breaking it or letting it expire while another user is accessing it. So I would write your own parsing function to duplicate a specific session in the database, like so:
Your session data is broken up like this in your dB:
__ci_last_regenerate|i:1450694483;
email|s:18:"amzadfof#gmail.com";
user_code|s:7:"AAA1787";
loginInId|i:8;
users_id|s:11:"00000000002";
active|s:1:"1";
username|s:13:"amzadmojumder";
fname|s:5:"Amzad";
lname|s:8:"Mojumder";
phone|s:11:"07900642131";
title|s:1:"#";
created_on|s:19:"2015-12-17 16:31:56";
last_login|s:19:"0000-00-00 00:00:00";
in_group|s:15:"2,1,3,4,5,6,7,8";
The basic architecture is as such:
{session_key}|{information type s=string, i=int}:{length}:"{value}";
So we can grab it from the database and parse through it
<?php
duplicateSession( $id_to_duplicate ) {
// Kill any current sessions we're in to prevent conflicts
$this->session->sess_destroy();
// Get the Session we want to duplicate
$this->db->where( 'id', $id_to_duplicate );
$session = $this->db->get( 'ci_sessions' );
$data = $session->row()->data;
// Turn our data into an array so we can parse through it
$data_arr = explode( ';', $data );
// Loop through each of our items to parse it out
foreach( $data_arr as $session_key ) {
// Explode out to separate our key name from our values
$session_key_arr = explode( '|', $session_key );
$key_index = $session_key_arr[0];
// Explode out to parse our values
$session_value_arr = explode( ':', $session_key_arr[1] );
$key_value = $session_value_arr[2];
// Build our new session index
$this->session->set_userdata( $key_index, $key_value );
}
}
?>
I have solved this problem by creating helper function to update session from existing session id.
Reference : https://forum.codeigniter.com/thread-61330-post-322814.html#pid322814
function updateSession( $session_id='' ) {
$ci =& get_instance();
// Kill any current sessions we're in to prevent conflicts
$ci->session->sess_destroy();
// Get the Session we want to duplicate
$ci->db->where( 'id', $session_id );
$session = $ci->db->get( 'ci_sessions' );
$row = $session->row();
if($row){
$session_db_data = $row->data;
$session_data = array(); // array where you put your "BLOB" resolved data
$offset = 0;
while ($offset < strlen($session_db_data))
{
if (!strstr(substr($session_db_data, $offset), "|"))
{
throw new Exception("invalid data, remaining: " . substr($session_db_data, $offset));
}
$pos = strpos($session_db_data, "|", $offset);
$num = $pos - $offset;
$varname = substr($session_db_data, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($session_db_data, $offset));
$session_data[$varname] = $data;
$offset += strlen(serialize($data));
}
$ci->session->set_userdata($session_data);
}
}

Virtuemart / User Fields

I have added a field in 'Manage User Fields' & when an email is sent to the administrator notifying them of the new user registration, I want to include this new field.
I have written some code to get this new field from #__vm_user_info in /administrator/components/com_virtuemart/classes/ps_shopper.php, in the _sendMail function, as well as added the variable to $message2.
ASEND_MSG has been modified to accept the parameter, but the field is not included in the email to the admin when a user is created. When I go look in the table, the data is there. So to trouble shoot, I hard coded a user name in the select statement, added another user & the correct value was sent for the hard coded user, not the one just added. I am now thinking that it is a commit issue with MySQL, so I put a sleep(4) in the code before I attempt to get the value...no luck.
Can anyone shine some light on this for me??
LarryR....
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to add with the following code in function add() before "return true" line :
/**************************** ***********************/
$pwd = $_POST['password'];
$db = JFactory::getDBO();
$query = "SELECT id, name, email, username"
. "\n FROM #__users"
. "\n ORDER by id DESC LIMIT 1"
;
$db->setQuery( $query );
$rows = $db->loadObjectList();
$namee = $rows[0]->name;
$emaill = $rows[0]->email;
$usern = $rows[0]->username;
$pwd;
$lid = $rows[0]->id;
$dbv = new ps_DB;
echo $query = "SELECT *"
. "\n FROM #__{vm}_user_info"
. "\n WHERE user_id=$lid"
;
$dbv->setQuery( $query );
$fid = $db->loadObjectList();
$field = $fid[0]->extra_field_1;
$user = clone(JFactory::getUser());
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0') {
JError::raiseError( 403, JText::_( 'Access Forbidden' ));
return false;
}
// If user activation is turned on, we need to set the activation information
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', md5( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
$component = 'com_user';
$activation_link = $mosConfig_live_site."/index.php?option=$component&task=activate&activation=".$user->get('activation');
$this->_sendMail( $namee , $emaill, $usern, $pwd, $activation_link);
/************************************************** Spinz ********************************************/
Note : Here we created the mail function for username and password to users mail.
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to comment the line in function register_save() before "return true" line:
// Send the registration email
//$this->_sendMail( $name, $email, $username, $password, $activation_link );
Note: Here the mail function generated we need to comment that mail functions and create another mail function in add() function of ps_shopper.php in first point.
administrator/components/com_virtuemart/classses/ps_shopper.php
Need to get the extra added field (extra_field_1) in jos_vm_user_info table in the function _sendmail() with following code and that field sent through the mail to user.
/****************************************************************/
$db = JFactory::getDBO();
$query = "SELECT id, name, email, username"
. "\n FROM #__users"
. "\n ORDER by id DESC LIMIT 1"
;
$db->setQuery( $query );
$rows = $db->loadObjectList();
$lid = $rows[0]->id;
$dbv = new ps_DB;
$query = "SELECT *"
. "\n FROM #__{vm}_user_info"
. "\n WHERE user_id=$lid"
;
$dbv->setQuery( $query );
$fid = $db->loadObjectList();
$field = $fid[0]->extra_field_1;
$subject = sprintf ($VM_LANG->_('SEND_SUB',false), $name, $mosConfig_sitename);
$subject = vmHtmlEntityDecode($subject, ENT_QUOTES);
if ($mosConfig_useractivation=="1"){
$message = sprintf ($VM_LANG->_('USEND_MSG_ACTIVATE',false), $name, $mosConfig_sitename, $activation_link, $mosConfig_live_site, $username, $pwd, $field );
} else {
$message = sprintf ($VM_LANG->_('PHPSHOP_USER_SEND_REGISTRATION_DETAILS',false), $name, $mosConfig_sitename, $mosConfig_live_site, $username, $pwd, $field);
}
/*************************************/
Note :
Initialize the variable "$field" get the extra added field value using query. Then that the extra field value is assigned by message section of the mail.(initialize variable $field having the a value added extra fields in virtuemart).
administrator/components/com_virtuemart/languages/common/english
replace the messages for the following code:
'USEND_MSG_ACTIVATE' => 'Hello %s,
Thank you for registering at %s. Your account is created and must be activated before you can use it.
To activate the account click on the following link or copy-paste it in your browser:
%s
After activation you may login to %s using the following username and password:
Username - %s
Password - %s
Degree - %s'
2.'PHPSHOP_USER_SEND_REGISTRATION_DETAILS' => 'Hello %s,
Thank you for registering at %s. Your customer account has been created.
You may login to %s using the following username and password:
Username - %s
Password - %s
Degree - %s
'
Note:
The extra added values assigned by the string %s in language file.
The message having the string values of extra added field value in virtuemart.
The degree shows the added extra field