Insert values with if condition with mysqli - php

I am trying to make register member page. If a new member insert an email which has been already exist, then there will be a notification saying that the email is exist. But if the email has not been exist, the values they insert in the form will be send to database.
I don't know what is wrong with my code bellow. It just blank and doesn't send anything to databse. I need a help.
<?php
//conection:
$link = mysqli_connect(".com","klaudia","intheclaud","elektro") or die("Error " . mysqli_error($link));
//consultation:
$member_id=$_GET['member_id'];
$member_name=ucwords(htmlspecialchars($_POST['member_name']));
$member_email=$_POST['member_email'];
$member_password=htmlspecialchars($_POST['member_password']);
$member_phone=$_POST['member_phone'];
$member_address_satu=ucwords(htmlspecialchars($_POST['member_address_satu']));
$member_address_dua=ucwords(htmlspecialchars($_POST['member_address_dua']));
$member_reference=$_POST['member_reference'];
$query = "SELECT * FROM member_registry WHERE member_email='$member_email '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)";
?>
I have tried to check the connection and the database. Everything works fine here. When I insert someone name which has been in the table of the database, it will echo that the email already exist. and vice versa.
$query = "SELECT * FROM member_registry WHERE member_name='Klaudia '" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = $link->query($query);
if (mysqli_num_rows($result) > 0) {
echo "This email you are using has been registered before";
}
else {
echo "This email you are using has NOT been registered before";
}
[UPDATE]
mysqli_query($link, "INSERT INTO member_registry (
'member_id',
'member_name',
'member_email',
'member_password',
'member_phone',
'member_address_satu',
'member_address_dua',
'member_reference')
VALUES (0,1,2,3,4,5,6,7,8)");
}
?>

You shouldn't handle this by two separate queries (at least without a transaction).
Instead create a unique index that doesn't allow the same email address twice in the table and check for the specific ER_DUP_ENTRY error code to detect doublets.
sscce:
<?php
define('MYSQL_ER_DUP_ENTRY', 1062);
$mysqli = new mysqli('localhost', 'localonly', 'localonly', 'test');
if ($mysqli->connect_errno) {
trigger_error('connection failed', E_USER_ERROR);
}
$result = $mysqli->query('
CREATE TEMPORARY TABLE soFoo (
id int auto_increment,
email varchar(128),
primary key(id),
unique key(email)
)'
);
if ( !$result) {
trigger_error('create table failed', E_USER_ERROR);
}
$stmt = $mysqli->prepare('INSERT INTO soFoo (email) VALUES (?)');
if (!$stmt) {
trigger_error('prepare failed', E_USER_ERROR);
}
$result = $stmt->bind_param("s", $email);
if ( !$result) {
trigger_error('bind_param failed', E_USER_ERROR);
}
foreach( array('email1', 'email2', 'email1') as $n=>$email ) {
echo $n, ' ', $email;
$result = $stmt->execute();
if ( $result ) {
echo " ok\r\n";
}
else {
if ( MYSQL_ER_DUP_ENTRY==$stmt->errno ) { // <-- here's the test for the duplicate entry
echo " duplicate\r\n";
}
else {
var_dump($stmt->errno, $stmt->error);
}
}
}
prints
0 email1 ok
1 email2 ok
2 email1 duplicate

You have an error in your syntax. You don't close your function.
Also you shouldn't use single quotes around your coumn names.
mysqli_query($link, "INSERT INTO member_registry (
`member_id`,
`member_name`,
`member_email`,
`member_password`,
`member_phone`,
`member_address_satu`,
`member_address_dua`,
`member_reference`)
VALUES (0,1,2,3,4,5,6,7,8)");

Related

php script wont add record to mysql

The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this

ODBC/MYSQL Insert a Query Result from ODBC to a databse in MYSQL

I'm connecting to a cloud database through an ODBC connection:
$conn = odbc_connect('MYDATABASE','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "SELECT DATETIME_ID, NAME, Sum(CNDROP) AS DATA
FROM MY_TABLE
WHERE DATETIME_ID>='2014-09-28:00:00:00'
and DATETIME_ID<='2014-09-28 23:00:00'
and NAME IN ('CC2')
GROUP BY DATETIME_ID, NAME ORDER BY DATETIME_ID, NAME";
$rs = odbc_exec($conn,$sql);
if (!$rs) {
exit("Consulta fallida");
}
$result = odbc_exec($conn,$sql) or die(exit("Error en odbc_exec"));
print odbc_result_all($result,"border=1");
odbc_close($conn);
I can get the data, and print the data, but now I need insert that data into a MySQL database into my computer.
I don't have any idea how to do it, so I need help with an example. I tried to search on google but nothing was helpful.
Option 1:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array('DATETIME' => odbc_result ($result, "DATETIME"),
'NAME'=> odbc_result ($result, "NAME"),
'CNDROP'=> odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
foreach($cloud_data as $data){
$sql = sprintf("INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES ( '%s','%s','%s')",
$data['DATETIME'], $data['NAME'], $data['CNDROP']);
$rs = odbc_exec($conn,$sql);
if (!$rs) {
error_log("Consulta fallida");
}
}
odbc_close($conn);
}
Option 2:
Function to SELECT
function get_data_from_cloud(){
$conn=odbc_connect('CLOUD','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT DATETIME, NAME, CNDROP
FROM TABLE1
WHERE DATETIME>='2014-09-28 00:00:00' and
DATETIME<='2014-09-28 23:00:00' and
NAME IN ('PETER')
GROUP BY DATETIME, NAME
ORDER BY DATETIME, NAME";
$result=odbc_exec($conn,$sql)or die(exit("Error en odbc_exec"));
$data = array();
while (odbc_fetch_row($result)) {
$data[]=array(odbc_result ($result, "DATETIME"),
odbc_result ($result, "NAME"),
odbc_result ($result, "CNDROP"));
}
return $data;
}
Function to INSERT
function insert_cloud_data($cloud_data=array()){
$conn=odbc_connect('LOCAL','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql = "INSERT INTO Prueba (DATIME, NAME, CNDROP)
VALUES (?, ?, ?)";
$stmt = odbc_prepare($conn, $sql);
if(!$stmt) die("could not prepare statement ".$sql);
foreach($cloud_data as $data){
odbc_execute($stmt, $data);
}
odbc_close($conn);
}
USAGE
$cloud_data = get_data_from_cloud();
insert_cloud_data($cloud_data);
Here is different approach.
Create $conn1 (cloud) and $conn2 (localhost). Query the $conn1 then use php while and insert command into $conn2.
$conn1 = (cloud);
$conn2 = (localhost);
$query = "SELECT ...";
$result = odbc_exec($conn1,$query);
while( fetch result data ) {
$query = "INSERT ....";
odbc_exec($conn2,$query);
}

data Not Storing

this is my connection class
class Connection {
public function query($sql){
mysql_connect('localhost','root','') or die("Connection error ". mysql_error());
mysql_select_db('liontours') or die("Database error ". mysql_error());
$results = mysql_query($sql);
$last_inserted_id = mysql_insert_id();
return array('results'=>$results, 'last_id'=>$last_inserted_id);
}
}
this is my model
public function V_reg($v_no, $dl_no, $owner, $o_name, $o_nic, $i_date, $ex_date, $p_report, $nic, $s_name, $f_name, $initials, $dob, $stat, $v_type) {
$sql = "INSERT INTO `vehicledetails`(`vehicle_no`, `owner`, `owner_name`, `owner_nic`, `insured_date`, `ex_date`, `police_report`,`type`)
VALUES ('$v_no','$owner','$o_name','$o_nic','$i_date','$ex_date','$p_report','$v_type')";
$conn = new Connection();
//vehicle id of last inserted record
$vehicle_id = mysql_insert_id();
$results = $conn->query($sql);
$last_vehicle_record_id = $results['last_id'];
$fk_key = $last_vehicle_record_id;
//checking the first table insert successful if so do the second insert else must define counter measure in else part
if ($fk_key !== 0) {
$sql1 = "INSERT INTO driverdetails (id, vehicle_id, nic,sir_name,first_name,dlNo,initials,dob,status )
VALUES ('null', '$fk_key', '$nic','$s_name','$f_name','$dl_no', '$initials','$dob','$stat')";
$results = $conn->query($sql1);
}else{
die('transaction failed').mysql_error();
}
return $results;
}
}
i don't know what is wrong with this coding but it's not passing the data all the time it says transaction failed and no error given. just the text can some body tell me any thing wrong with this coding ? if there is no coding errors is it a problem with my database ?

PHP - Fatal error: Call to a member function bind_param() on a non-object -

This script is used with an Android app
The error :
2 Fatal error: Call to a member function bind_param() on a non-object in ** on line 36
There is three sql queries on my script the first one is running correctly but the two other one not.
I don't really understand why because I do exactly the same stuff ...
PHP
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
$con = mysqli_connect("******","******","******","******");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// If all the input are ok
if(isset($_REQUEST['firstName']) AND isset($_REQUEST['lastName']) AND isset($_REQUEST['phone']) AND isset($_REQUEST['linkedPhone']) AND isset($_REQUEST['imei'])) {
$firstname = $_REQUEST['firstName'];
$lastName = $_REQUEST['lastName'];
$phone = $_REQUEST['phone'];
$linkedPhone = $_REQUEST['linkedPhone'];
$imei = $_REQUEST['imei'];
$req = $con->prepare('SELECT idUser FROM user WHERE phone = ?');
$req->bind_param("s", $_REQUEST['linkedPhone']);
$req->execute();
$req -> bind_result($idFollowed);
$result = $req->fetch();
$idFollowed = "".$idFollowed;
echo $idFollowed;
// if linkedPhone doesn't exist
if(!$result) {
$return['result'] = "Linked phone doesn't exist";
}
else {
$req2 = $con->prepare('INSERT INTO user (firstName, lastName, phone, idFollowed, imei) VALUES (?, ?, ?, ?, ?)');
// Work using phpMyAdmin
// INSERT INTO user (firstName, lastName, phone, idFollowed) VALUES ('Gael', 'Fontenelle', '01234', '1');
$req2->bind_param("sssss", $_REQUEST['firstName'], $_REQUEST['lastName'], $_REQUEST['phone'], $idFollowed, $_REQUEST['imei']); // ERROR HERE
$req2->execute();
// Find the id of the new user
$req3 = $con->prepare('SELECT idUser FROM user WHERE phone = ?');
$req3->bind_param("s", $_REQUEST['phone']); // ERROR HERE
$req3->execute();
$req3 -> bind_result($idUser);
$result = $req->fetch();
if(!$result) {
$return['result'] = "Error in the registration process";
}
else {
$return['result'] = "".$idUser;
}
}
}
else {
// Display the error
$return['result'] = "Missing data!";
}
echo json_encode($return);
}
mysqli_close($con);
?>
SQL
CREATE TABLE user (
idUser int NOT NULL auto_increment,
firstName varchar(50) NOT NULL,
lastName varchar(50) NOT NULL,
phone varchar(50) NOT NULL,
idFollowed int default 0, -- 0 if it's the primary user
validation boolean NOT NULL, default 0, -- 1 = VALIDATION OK
imei varchar(50) NOT NULL,
PRIMARY KEY (idUser),
FOREIGN KEY (idFollowed) REFERENCES idUser (user)
);
INSERT INTO user (firstName, lastName, phone, imei) VALUES
('Steve', 'Jobs', '0836656565651', '23456789765'),
('Steve', 'Wozniak', '0836656565652', '23456789765'),
('Bill', 'Gates', '0836656565653', '23456789765'),
('Steve', 'Balmer', '0836656565654', '23456789765'),
('Larry', 'Pagen', '0836656565655', '23456789765'),
('Serguei', 'Brin', '0836656565656', '23456789765');
That means that your sql query failed due to an error. Here you have a problem on how you set up the connection and consequently the $con object. Well try this
$con = new mysqli("myhost","myusrname","mypwd","mydb");
/*then check connection */
if($con->connection_error)
{
die("error in connecting to database");
}
/*Proceed with the rest here */
You forgot the
new
keyword
You may also have an sql error in the prepare field. You can check the error this way
$resq = $con->prepare("......");
if(!$resq)
{
die("prepare failed ".$con->error);
}
$req2->bind_param("sssis",$_REQUEST['firstName'], $_REQUEST['lastName'], $_REQUEST['phone'], $idFollowed, $_REQUEST['imei']);
your fourth parameter is int Replaced 'sssss' to 'sssis'

how to set the variable in a mysql statement into user selection from a dropdown list

I am creating an onlineshop. The user add the details of a new product using a text-based fields for Title,Price,Description but it chooses where to upload the product using a drop down list with all the tables from the database.
The problem is, how do I set his selection to be the statement in my insert.php file, in order for the uploading of a new file to depend on his selection??
insert.php
<?php
$con=mysqli_connect('localhost','root', '',"onlineshop");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO **--SELECTION OF THE USER FROM DROPDOWN--** (title, description, price)
VALUES
('$_POST[title]','$_POST[description]','$_POST[price]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
dropdown.php
<?php
$dbname = 'onlineshop';
if (!mysql_connect('localhost', 'root', '')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "No tables exist! \n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = '';
while ($row = mysql_fetch_row($result)) {
$tables .="<option value='$row[0]'>$row[0]</option>";
}
mysql_free_result($result);
?>
index.html (form for the dropdown list)
<?php
include_once 'dropdown.php';
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<select id = "form3" name="Tables" id="ddTables">
<?php
echo $tables;
?>
</select>
<input type="submit" id="tableSubmit" value="Submit"/>
</form>
Please if anyone can suggest anything I will really aprrieciate this. I don't think is something too hard, but for me it is!
Thanks!
connect.php
<?php
// Try to connect to MySQL
$connect = mysql_connect('localhost','root', '') or die('Sorry could not connect to database');
// Check connect and return error if failed
$use_db = mysql_select_db('onlineshop');
$create_db = "CREATE DATABASE onlineshop";
if(!$use_db) {
echo mysql_error();
mysql_query($create_db);
mysql_select_db('onlineshop');
}
$con=mysqli_connect('localhost','root', '');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE onlineshop";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($con);
}
//main table
$sql = 'CREATE TABLE mens( '.
'id INT NOT NULL AUTO_INCREMENT, '.
'title VARCHAR(20) NOT NULL, '.
'description VARCHAR(45) NOT NULL, '.
'price FLOAT NOT NULL, '.
'image varchar(200),'.
'image_small varchar(200),'.
'primary key ( id ))';
//copy attributes of the main table
$sql2= 'CREATE TABLE women AS ( SELECT * FROM mens where 1=2)';
$sql3= 'CREATE TABLE kids AS ( SELECT * FROM mens where 1=2)';
$sql4= 'CREATE TABLE infants AS ( SELECT * FROM mens where 1=2)';
$sql5= 'CREATE TABLE baby_books AS ( SELECT * FROM mens where 1=2)';
$sql6= 'CREATE TABLE garden AS ( SELECT * FROM mens where 1=2)';
$sql7= 'CREATE TABLE comics AS ( SELECT * FROM mens where 1=2)';
$sql8= 'CREATE TABLE cooking AS ( SELECT * FROM mens where 1=2)';
$sql9= 'CREATE TABLE moviestv AS ( SELECT * FROM mens where 1=2)';
$sql10= 'CREATE TABLE music AS ( SELECT * FROM mens where 1=2)';
$sql11= 'CREATE TABLE games AS ( SELECT * FROM mens where 1=2)';
$retval = mysql_query( $sql, $connect );
$retval2 = mysql_query($sql2, $connect);
$retval3 = mysql_query($sql3, $connect);
$retval4 = mysql_query($sql4, $connect);
$retval5 = mysql_query($sql5, $connect);
$retval6 = mysql_query($sql6, $connect);
$retval7 = mysql_query($sql7, $connect);
$retval8 = mysql_query($sql8, $connect);
$retval9 = mysql_query($sql9, $connect);
$retval10 = mysql_query($sql10, $connect);
$retval11 = mysql_query($sql11, $connect);
//this checks only for table1, check for all of them
if(! $retval)
{
die('Could not create table: ' . mysql_error());
}
echo "Tables created successfully\n";
?>
Tested code that does as asked. It uses 'mysqli' as object. The code escapes input. and the tablename is validated (not any more).
Note: all form field names are assumed to be lowercase.
PHP 5.3.18, MySQL 5.5.16.
<?php session_start();
$mysqli = new mysqli('localhost', 'test', 'test',"testmysql");
// Check connection
if ($mysqli->connect_error)
{
echo "Failed to connect to MySQL: " . $mysqli->error;
}
// removed table validation check...
// $validTableNames = array('my_table_1', 'my_table_2', 'another_table_3');
$tablename = isset($_POST['tablename']) ? $mysqli->real_escape_string($_POST['tablename']) : '';
// $tableNameOk = in_array($tablename, $validTableNames);
// if (!$tableNameOk) {
// die('Error: Invalid table name:' . $tablename);
// }
$title = !empty($_POST['title']) ? $mysqli->real_escape_string($_POST['title']) : null;
$description = !empty($_POST['description']) ? $mysqli->real_escape_string($_POST['description']) : null;
$price = !empty($_POST['price']) ? $mysqli->real_escape_string($_POST['price']) : null;
$sql = "INSERT INTO `{$tablename}` (title, description, price) VALUES (?, ?, ?)";
$stmt = $mysqli->prepare($sql);
// We need to 'bind' the three input variables to the there '?' in the query.
// 'sss' indicates that the parameters are 'strings'.
// the order must match the order of the column names.
$stmt->bind_param("sss", $title, $description, $price);
$allOk = $stmt->execute();
if (!$allOk)
{
die('Error: ' . $mysqli->error);
}
echo "1 record added";
$mysqli->close();
?>
you should not mention table name in your insert query,
error for your code:
$sql="INSERT INTO **--SELECTION OF THE USER FROM DROPDOWN--** (title, description, price)
VALUES('$_POST[title]','$_POST[description]','$_POST[price]')";
try this:
$sql="INSERT INTO `tablename` (title, description, price)VALUES(?,?,?)";
You can do exactly the same as with your values: $_POST['Tables'].
But this code is very unsafe.
At least you should add mysqli_real_escape string around you $_POST values.
Preferably you use a prepaired statement and params:
$stmt = $mysqli->prepare("INSERT INTO ? (title, description, price) VALUES(?,?,?)");
$stmt->bind_param("ssss", $_POST['Tables'], $_POST[title], $_POST[description], $_POST[price]);
$stmt->execute();

Categories