Im just beginner and a cant understand why my code generates same identical rows after inserting it. please help me.
here is my html code:
<form id="sing" action="signup.php" method="POST">
<input type="text" name="first" placeholder="სახელი"> <br>
<input type="text" name="uid" placeholder="მომხმარებელი"> <br>
<input type="password" name="pwd" placeholder="პაროლი"> <br>
<button type="submit">რეგისტრაცია</button>
</form>
php:
include 'dbh.php';
$first = $_POST['first'];
$uid = $_POST['uid'];
$pwd = $_POST['pwd'];
$sql = "INSERT INTO user (first, uid, pwd)
VALUES ('$first', '$uid', '$pwd')";
$result = mysqli_query($conn, $sql);
if (!mysqli_query($conn, $sql)) {
echo "maica joo";
} else {
echo "kaia";
}
That's because mysqli_query($conn, $sql) is called twice, change the code to:
$result = mysqli_query($conn, $sql);
if (!$result) {
echo "maica joo";
} else {
echo "kaia";
}
you are running mysqli_query() twice!! So it creates 2 identical rows.
// first time it insert a row
$result = mysqli_query($conn, $sql);
// now you run it again and it creates that row again
if (!mysqli_query($conn, $sql)) {
echo "maica joo";
} else {
echo "kaia";
}
Amend this to
// first time it insert a row
$result = mysqli_query($conn, $sql);
// now test $result to see if the query failed
if (!$result) {
echo "maica joo";
} else {
echo "kaia";
}
You are running the query twice with the two mysqli_query.
Change it to:
$result = mysqli_query($conn, $sql);
if (!$result) {
Related
I need to insert many values from checkbox but only the last value is inserting to database.
HTML CODE:
<?php
$conn = mysqli_connect("localhost", "root", "", "fix_in_time");
$result = mysqli_query($conn, "SELECT * FROM `material` WHERE id > 0");
while($row = mysqli_fetch_assoc($result)):?>
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo" id="Tipo"><label><?php echo $row['tipo'];?></label><br>
<?php endwhile;?>
There is the PHP CODE:
$Sala = mysqli_real_escape_string($conn, $_POST['Sala']);
$Descricao = mysqli_real_escape_string($conn, $_POST['Descricao']);
$Tipo = mysqli_real_escape_string($conn, $_POST['Tipo']);
$Data = date("d-m-Y H:i:s", strtotime('-1 hour'));
if(empty($_POST['Sala']) || empty($_POST['Descricao'])||
empty($_POST['Tipo'])){
echo"<script language='javascript' type='text/javascript'>alert('Por favor
preencha os campos!');window.location.href='../index.php';</script>";
exit();
}
if(isset($_POST['submit'])){
if (!empty($_POST['Tipo'])) {
foreach ((array)$Tipo as $Tipo) {
$query = "INSERT INTO `relatorios` (Data, Sala, Descricao, Tipo) VALUES ('$Data', '$Sala', '$Descricao', '$Tipo')";
mysqli_query($conn, $query);
}
}
}
In your html code change input tag to:
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo[]">.
If you append tag name with [], then this post variable in php will be an array. I've removed tag id because it should be unique, not sure if you need it, but if you do, then make it unique.
And your php code should look something like this:
if(isset($_POST['submit'])) {
if (!empty($_POST['Tipo']) && is_array($_POST['Tipo'])) {
foreach ($_POST['Tipo'] as $Tipo) {
$TipoEscaped = mysqli_real_escape_string($conn, $Tipo);
$query = "INSERT INTO `relatorios` (Tipo) VALUES ('$TipoEscaped')";
$success = mysqli_query($conn, $query);
if (!$success) {
//handle mysql error
}
}
}
}
How can I submit a table row data to another table using an input field in PHP and MYSQL?
HTML
<form method="post" action="post.php">
<input type="number" name="code" placeholder="Code..."/>
<input type="submit" name="submit" value="Submit"/>
</form>
Post.php
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
mysqli_query($connection, $getCode);
if ($_POST['code'] == $code) {
$migrating = "INSERT INTO managment(price) VALUES ($price) SELECT
price FROM products";
mysqli_query($connection, $migrating);
header("location: index.php");
}
}
What is wrong with my code?
The syntax is :
INSERT INTO managment(price) SELECT price FROM products
Maybe you want add a WHERE clause :
INSERT INTO managment(price) SELECT price FROM products WHERE code=$code
Note: in your code, $_POST['code'] == $code doesn't make sense, because of $code = $_POST['code'] earlier.
I also suggest you to have a look to How can I prevent SQL injection in PHP? to secure your queries.
Your code updated (untested) :
if (isset($_POST['submit'])) {
$code = $_POST['code'];
$getCode = "SELECT * FROM products WHERE code=$code";
$result = mysqli_query($connection, $getCode);
if (!$result) die("Error: " . mysqli_error($connection));
$row = mysqli_fetch_assoc($result);
if ($row['code'] == $code) {
$migrating = "INSERT INTO managment(price)
SELECT price FROM products WHERE code=$code";
$result2 = mysqli_query($connection, $migrating);
if (!$result2) die("Error: " . mysqli_error($connection));
header("Location: index.php");
exit;
}
}
this is my login.php file
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name=$password="" ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = testInput($_POST["name"]);
$password = testInput($_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
//echo "Name ".$_POST["name"];
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")){
if($result->num_rows > 1){
echo "you are logged in";
while ($row = $result->fetch_assoc()){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
$result->close();
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
$conn->close();
?>
</body>
</html>
One problem is that my query
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")) returns column names as one row. I don not know whether it is ok ? The other thing whether I put wrong name or password or correct , in both cases I do not get any output. What I am doing wrong here ? And if you can please tell me how to write a mysqli query in php with correct format with a comprehensive example . I searched on google but there are different ways so I am confused specially when column names and variables come in the query.
Your test_input function is weak/unsafe, also, mysql_query is depricated, use mysqli and prepared statements as explained here: http://php.net/manual/en/mysqli.prepare.php
Furthermore, I included a section of code I use for my login system (bit more sophisticated using salts etc, you should be able to compile it in a piece of script suitable for you.
//get salt for username (also check if username exists)
$stmtfc = $mysqli->stmt_init();
$prep_login_quer = "SELECT salt,hash,lastlogin FROM users WHERE name=? LIMIT 1";
$stmtfc->prepare($prep_login_quer);
$stmtfc->bind_param("s", $username);
$stmtfc->execute() or die("prep_login_quer error: ".$mysqli->error);
$stmtfc->store_result();
if ($stmtfc->num_rows() == 1) {
$stmtfc->bind_result($salt,$hash,$lastlogin);
$stmtfc->fetch(); //get salt
$stmtfc->free_result();
$stmtfc->close();
I don't know what do you mean but thats how i query mysqli
$query = mysqli_query($db, "SELECT * FROM users WHERE name='$name' AND password='$password'");
if($query && mysqli_affected_rows($db) >= 1) { //If query was successfull and it has 1 or more than 1 result
echo 'Query Success!';
//and this is how i fetch rows
while($rows = mysqli_fetch_assoc($query)) {
echo $rows['name'] . '<br />' ;
}
} else {
echo 'Query Failed!';
}
i think thats what you mean
EDIT:
<?php require ("database_connect.php");?>
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"])?>">
Name : <input type="text" name="name"><br/>
Password : <input type = "text" name="password"><br/>
<input type="submit" name="login" value="Log In">
</form>
<?php
$name = null ;
$password= null ;
if($_SERVER["REQUEST_METHOD"]=="POST" and isset($_POST["login"])){
$name = mysqli_real_escape_string($conn, $_POST["name"]); //I updated that because your variables are not safe
$password = mysqli_real_escape_string($conn, $_POST["password"]);
}//if ends here
//testInput function
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
}//testInput ends here
if(isset($_POST["login"]) && isset($_POST["name"]) && isset($_POST["password"]) && !empty($_POST["name"]) && !empty($_POST["password"])){
if($result = mysqli_query($conn,"SELECT * FROM users WHERE name='{$name}' and password='{$password}'")){
print "rows are ".mysqli_num_rows($result)"<br>";//number of rows
if($result && mysqli_affected_rows($conn) >= 1){//If query was successfull and it has 1 or more than 1 result
echo "you are logged in<br>";
while ($row = mysqli_fetch_assoc($result)){
echo "Name ".$row["name"]."-Password ".$row["password"];
}//while loop ends here
}//if ends here
/* free result set */
mysqli_free_result($result);
}
else{
print "Wrong Credentials "."<br>";
die(mysqli_error($conn));
}
}
//close connection
mysqli_close($conn);
?>
</body>
</html>
try to change this query
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password'")
to
$result = mysqli_query($conn,"SELECT * FROM users WHERE name='$name' and password='$password' limit 1")
then you will get only one row , and try to change
$row = $result->fetch_assoc()
to
$row = $result->mysqli_fetch_row()
then you can display the results by colomn number instead of colomn name
<?php
mysql_connect("abc.com","user","password");
mysql_select_db("database name");
$query1="select * from table_name";
$exe1= mysql_query($query1);
$row= mysql_fetch_assoc($exe1);
if($row["email"]==$_POST["email"] && $row["[password"]==$_POST["password"]) {
echo "Login successfully";
} else {
echo "error in login";
}
?>
enter your column name in row["email"] and $row["password"]
i'm trying to delete a row from database and i`m using the following code. When i submit the page reloads and if i check the db the row is still there. No error, no nothing. What can i do to solve this?
HTML
<div class="delete_row">
Sterge
<form method="post" action="">
*<input type="text" name="id_col" Placeholder="Id-ul coloanei"><br>
<input type="submit" name="submit1" value="Sterge">
</form>
</div>
PHP
$id_stergere=isset($_POST["id_col"]);
$submitcheck2=isset($_POST["submit1"]);
if($submitcheck2 && $id_stergere !==0 ){
$sql = "DELETE FROM evenimente WHERE ID_even=$id_stergere";
$result = query_mysql($sql);
}
if (isset($_POST["id_col"]))
$id_stergere=$_POST["id_col"];
if (isset($_POST["submit1"]))
$submitcheck2=$_POST["submit1"];
//additional check:
// if (!is_numeric($id_stergere)) die('there was a problem');
// if (!$submitcheck2) die('there was a problem');
$sql = "DELETE FROM evenimente WHERE ID_even=".$id_stergere;
$result = mysql_query($sql);
query_mysql?
Use this for your php :
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit1'])){
$id_stergere=$_POST["id_col"];
$submitcheck2=$_POST["submit1"];
if($submitcheck2 && $id_stergere){
$sql = "DELETE FROM evenimente WHERE ID_even=$id_stergere";
$result = mysql_query($sql);
}
}
You should be using mysqli instead though.
Use this instead of the $sql = and $result = :
$link = mysqli_connect("localhost","db","password","user") or die("Error " . mysqli_error($link));
$query= "DELETE FROM evenimente WHERE ID_even=$id_stergere";
$result= mysqli_query($link,$query);
To get the numrows use this:
$numrows = $result->num_rows;
For a fetch_array:
while($row = $result->fetch_array()){
$var= $row['field'];
}
UPDATE: Add error_reporting(E_ALL ^ E_NOTICE); to the top of php script.
Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']