Mysqli not inserting data on table - mysqli

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.

Related

multi_query not working when creating registers on tables

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);
}

Mysqli bind_result error

I am new to SQL and PHP. My goal is simple: Check if there is already an email adress stored in database. I am using following code:
$email = info#test.pl;
$conn = new mysqli("localhost", "root", "", "mysite"); // Create connection
if ($conn->connect_error) { // Check connection
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("SELECT * FROM contacts WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($email);
$stmt->store_result();
$result = $stmt->num_rows;
echo $result;
Every time i get an error. It says i am using wrong numbers of parameters in bind_result. How it can be?
If you're new to all this, I would recommend using PDO instead of mysqli.
As for your error: you select * columns but bind only one.
You can change the query to select email, or do away with binding the resultset:
if all you want is to check for the presence of the email, all you need is the rowcount.

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

Postgresql lowercase to compare data

I want to get the contents from a row in the Postgresql database and compare the lowercase version of it to a lowercase version of a user input to check if it exists in the database.
i tried:
"SELECT LOWER(name) FROM user_names WHERE name LIKE '%$search%' ORDER BY name ASC"
but that make query not working at all.
EDIT
I am trying to implement an autocomplete Jquery UI like here:
http://jqueryui.com/demos/autocomplete/#remote
for search box (for names)
using javascript and php.
php code:
$search = ($_GET['term']);
if (!$con)
{ die('Could not connect: ' . pg_last_error ());}
else
{
$sql = "SELECT name FROM users_table WHERE name LIKE '%$search%' ORDER BY name ASC";
$result = pg_query($sql);
$json = '[';
$first = true;
while ($row = pg_fetch_array($result))
{
if (!$first) { $json .= ','; } else { $first = false; }
$json .= '{"value":"'.$row['name'].'"}';
}
$json .= ']';
echo $json;
exit();
}
JavaScript code:
$(document).ready(function()
{
$('#auto').autocomplete(
{
source: "./file.php",
minLength: 3
})
})
all above work great.. exactly like in Demo here: http://jqueryui.com/demos/autocomplete/#remote
my problem is that the names in database stored in Uppercase (e.g. LORI)
and of course the user prefers to insert a lowercase in search box to search for name (e.g. lori). but since it stored in uppercase, i need to convert it.
i tried as your suggestion :
$sql = "SELECT LOWER(name) FROM users_table WHERE name ILIKE '%$search%' ORDER BY name ASC";
then i got an empty drop down list!
pretty weird!
thanks in advance.
Google is your friend:
SELECT LOWER(name) FROM user_names
WHERE name ILIKE '%$search%' ORDER BY name ASC

PDO Prepared Select statement for checking if a user exists

I'm a pdo newbie and need to prepare and execute some php/pdo code:
This code works to allow me to create users in my database:
// Perform Insert / Update
$STH = $dbh->prepare("INSERT INTO users (username, email) values (:username, :email)");
$STH->bindParam(':username', $username);
$STH->bindParam(':email', $email);
try{
$STH->execute();
redirect_to(signupsuccess.php);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
but before I put that data into the database I need to do a check to make sure the email doesn't already exist in the database. I need to do a SELECT, something like:
$STH = $dbh->prepare("SELECT FROM users (email) values (:email)");
$STH->bindParam(':email', $email);
try{
$STH->execute();
}
and I know I need to add
"WHERE something matches '$_POST'email') something.." ...
I'm totally lost at this point..I can do this without PDO but I want to start using PDO's prepared statements..Please help!
Just do a simple select. I recommend Using bind value if you may possibly have a null email.
$STH = $dbh->prepare("SELECT email FROM users WHERE email = :email");
$STH->bindValue(':email', $email);
try{
$STH->execute();
}
Then just check if any records are returned. If so, Update, don't insert. good luck.