why data cannot post to database? [duplicate] - php

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm trying to insert data into the database, it run my coding and i get output as 'SOP data Added Successfully', but the data does not get into the database.
if (isset($_SESSION['admin_id']))
{
include 'databaseConnection.php';
if (isset($_POST['add_btn']))
{
$sop_name = $_POST['sop_name'];
$sop_step = $_POST['sop_step'];
$sop_comment = $_POST['sop_comment'];
$department_id = $_POST['department_id'];
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM sop WHERE sop_name = '$sop_name' && admin_id = '".$_SESSION['admin_id']."'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
if ($count == 1)
{
echo '<script language="javascript">';
echo 'alert("SOP Data Already Existed")';
echo '</script>';
}
else
{
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
echo '<script language="javascript">';
echo "alert('SOP Data Added Succesfully'); window.location.href='dashboardOrganizationDepartment.php'";
echo '</script>';
}
}
?>
I expect that the result can be post into the database, but it is not. There is also not showing any errors for me to refer.

Can you put some try catch within your insert query, you will get the actual error in query
try {
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
} catch (Exception $e) {
die($e->getMessage());
}

Related

Why this PHP code return me always the same echo? [duplicate]

This question already has answers here:
PDO query is always returning 1 or true
(2 answers)
Closed 3 years ago.
This code is a part of registration code. But it return always "Nickname already exist". I don't understand why.
if (isset($_POST['create'])) {
$nickname = $_POST['nickname'];
$email = $_POST['email'];
$password = $_POST['password'];
$slt1 = "SELECT nickname FROM users WHERE nickname='$nickname'";
$slt2 = "SELECT email FROM users WHERE email='$email'";
$stmt1 = $db->prepare($slt1);
$stmt2 = $db->prepare($slt2);
if($stmt1->execute([$nickname])) {
echo 'Nickname already exist';
} elseif ($stmt2->execute([$email])) {
echo 'email already exist';
} else {
//more code here
}
}
The way you use execute is wrong, and what an execute returns is a Boolean value (TRUE/FALSE) but not the number of rows your query has selected/affected.
So you need to get the count of the rows that your query affects and perform the "if" on that value.
Like this,
$stmt1->execute();
$number_of_rows = $stmt1->num_rows;
if($number_of_rows == 1){
echo 'Nickname already exist';
}
else{
//your code to insert data
}

if empty query show messages in php [duplicate]

This question already has answers here:
How do I check db query returned results using PHP's PDO
(3 answers)
Closed 6 years ago.
I need little help with my code.
I want to show message when table is empty.
My code is
function category()
{
global $config,$db,$lang;
$result = "SELECT id, name FROM category ORDER BY id";
$stmt = $db->prepare($result);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$tpl=parse_tpl('category.php');
$tpl=str_replace("{_HTTP_SERVER_}",$config['http_server'],$tpl);
$tpl=str_replace("{cat_id}",$row['id'],$tpl);
$tpl=str_replace("{cat_title}",kill_tags($row['name']),$tpl);
echo $tpl;
}
if(empty($row)) echo $lang['category_not'];
}
When no records in table show this message
$lang['category_not']
I tried with if(empty($row)) , if (!$row) and if($row == o) but didn't work.
You have to use your code as following way:
if($stmt->rowCount() == 0)
{
echo "nothing found message";
}
else
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC)
{
// code for loop
}
}// else ends here

PHP MySql - Check if column B matches GET input [duplicate]

This question already has an answer here:
PHP MySql - Check if value exists
(1 answer)
Closed 8 years ago.
I've got a database table with two columns:
EMAIL_ADDRESS and ACTIVATION_CODE
I need to make the script check if the Activation Code the user has submitted in the URL, matches the Email Address in the table. So far this isn't working.
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if ($result = '$acticode') {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}
check row with mysql_num_row
if(mysql_num_rows($result)>0){...}
and check valid code with
if(mysql_error())
You need to know the column in the database where the code is stored, also, you need to actually get the data
$email = mysql_real_escape_string($_GET['email']);
$acticode = mysql_real_escape_string($_GET['code']);
$code_found = false;
$result = mysql_query("SELECT * FROM xActivate WHERE EMAIL_ADDRESS='$email',1");
if($result) {
$row = mysql_fetch_assoc($result);
if($row) {
if ($row['codefield'] == $acticode) {
$code_found = true;
}
}
}
if($code_found) {
echo 'Code is valid';
} else {
echo 'Code is NOT valid';
}

checking if a record is already present in mySQL database [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
insert contacts into database but does not want to duplicate already existing contact
what i intend to do is, check if a user's account is already stored in my database, redirect to another url else store his data in the database. following is the query i wrote. it is not working please suggest where i went wrong.
thaks.
$result = mysql_query("SELECT * FROM centraluser where id = '$id'");
$row = mysql_fetch_row($result);
if($row) {
mysql_query("UPDATE central SET time = '$time' WHERE id = '$id'");
$url = "http://www.somesite.com";
echo '<script type="text/javascript"> alert("Sorry! you can't register twice.");</script>';
echo '<script type="text/javascript">top.location.href = "'.$url.'";</script>';die;exit;
}
else {
mysql_query("INSERT INTO centraluser VALUES ('$id','$name','$email','0','5000','0','0','$birthday','$time')");
echo('welcome new user');
First of all you are having the error with this code
escape string and use this code below.
and define what part of your code is still not working.
echo '<script type="text/javascript"> alert("Sorry! you can\'t register twice.");</script>';
echo '<script type="text/javascript">top.location.href = "'.$url.'";</script>';die;exit;
Hope this works
$result = mysql_query("SELECT * FROM centraluser WHERE id = '$id'");
$user_data = mysql_fetch_row($result);
if(empty($user_data)) {
$qry = "INSERT INTO centraluser VALUES ('$id','$name','$email','0','5000','0','0','$birthday','$time')";
mysql_query($qry);
$_SESSION['msg'] = 'welcome new user';
header("Location:dashboard.php"); // write your main page after login
exit();
}
else {
$qry="UPDATE central SET time = '$time' WHERE id = '$id'";
mysql_query($qry);
$url = "http://www.somesite.com";
echo '<script type="text/javascript"> alert("Sorry! you can\'t register twice.");</script>';
echo '<script type="text/javascript">top.location.href ="'.$url.'";</script>';
exit();
}

Best way to check for existing user in mySQL database? [duplicate]

This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.

Categories