Php and mysql insert [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have the next code, but it inserts two rows in the mysql database instead of one. Could ypu please take a look to the code?
Regards.
<?php
$name= $_POST['name'];
$password = $_POST['password'];
mysql_connect("localhost","username","mypass");
mysql_select_db("databaseName");
mysql_query($query ="insert into users(name,password) values ('$name','$password')");
if (mysql_query($query) === TRUE) {
echo "Record saved";
} else {
echo "Error";
}
?>

Don't call mysql_query() when you assign the $query variable. And remember to escape your data, since you're not using prepared statements.
mysql_connect("localhost","username","mypass");
$name = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['password']);
$query ="insert into users(name,password) values ('$name','$password')";
if (mysql_query($query)) {
echo "Record saved";
} else {
echo "Error: " . mysql_error();
}

Dont use the mysql_query function twice,
you want to check it in if statement, then dont call it before if clause.
See this following code.
$query ="insert into users(name,password) values ('$name','$password')"
if (mysql_query($query) === TRUE) {
echo "Record saved";
} else {
echo "Error";
}

Related

SQL Insert duplicating values [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm trying to insert data in SQL table, but it's duplicating the values:
$star1 = trim($_GET['star1']);
$star2 = trim($_GET['star2']);
$star3 = trim($_GET['star3']);
$star4 = trim($_GET['star4']);
$star5 = trim($_GET['star5']);
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Desculpe.. Falha ao salvar ");
}
$sql = "INSERT INTO classificacoes (nossa_empresa, produtos_oferecidos,atendimento, colaboradores, indicaria) VALUES ('$star1','$star2','$star3','$star4', '$star5')";
$conn->query($sql);
if ($conn->query($sql) != TRUE){
echo "Erro ao gravar";
}
else{
echo "Gravou";
}
mysqli_close($conn);
That is: The code insert two identincal values in the table.
What's wrong?
The problem is you're running the query twice:
$conn->query($sql);
if ($conn->query($sql) != TRUE){
The if line is also running the query, so you should remove the line above the if. Your code should be like this:
$sql = "INSERT INTO classificacoes (nossa_empresa, produtos_oferecidos,atendimento, colaboradores, indicaria) VALUES ('$star1','$star2','$star3','$star4', '$star5')";
if ($conn->query($sql) != TRUE){
echo "Erro ao gravar";
}
Or another option is to get the result of the query in a variable, like this:
$sql = "INSERT INTO classificacoes (nossa_empresa, produtos_oferecidos,atendimento, colaboradores, indicaria) VALUES ('$star1','$star2','$star3','$star4', '$star5')";
$insertOK = $conn->query($sql)
if ($insertOK != TRUE){ // This is equal to if(!$insertOK){
echo "Erro ao gravar";
}

How to delete row using php? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm using PHP to display what is in my MySQL database in a table. I think it is working but the output is still "ERROR". I need to delete all records in a row.
<?php
require_once ('config.inc.php');
$id=$_POST['id'];
$sql = "DELETE `subject_information` WHERE `id`='$id'";
$result = mysql_query($sql);
if ($result)
{
echo "Deleted Successfully";
}
else
{
echo "ERROR!";
mysql_close();
}
?>
You forgot your FROM keyword. The proper syntax is:
DELETE FROM table_name
WHERE some_column=some_value;
So your code should be like this:
$sql = "DELETE FROM `subject_information` WHERE `id`='$id'";
you should change this line :
$sql = "DELETE `subject_information` WHERE `id`='$id'";
to
$sql = "DELETE FROM `subject_information` WHERE `id`='".$id."'";
First you should output the error that is returned from the database:
if ($result)
{
echo "Deleted Successfully";
}
else
{
echo mysql_error();
}
Second: the mysql_xxxx functions will be removed from PHP in future version. You should have a look at PDO to connect to your database
Syntax of your query has to be changed for deleting a row from table use following syntax
$sql = "DELETE FROM tablename WHERE id='$id'";
off topic, but please read http://php.net/manual/security.database.sql-injection.php
this type of query is vulnerable for SQL-Injections, because you don't check/quote your $id.
As a hint, these functions may help you:
mysql_real_escape_string
ctype_digit
is_numeric

use session username as "WHERE" in mysqli query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I know I am doing something wrong but I really would like to know what it is. I can echo the
username of the session loggedin user using <?php echo $_SESSION['username']; ?>but I don't know why it doesn't work when I try to query database using the same technique. my codes below
I include this in the page
<?php
session_start();
$username=$_SESSION['username'];
?>
and here is the code that was suppose to display firstname and user_id of the sessions logged in user
<?php
$conn = new mysqli('localhost', 'root', 'browser', 'test');
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
$username = '$username';
$sql = "SELECT `user_id`, `firstname` FROM `members` WHERE `username`='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<br /> user_id: '. $row['user_id']. ' - firstname: '. $row['firstname'];
}
}
else {
echo '0 results';
}
$conn->close();
?>
$username = '$username';
PHP variables inside single-quotes are not expanded. So now your variable is the literal string '$username', which undoubtedly won't match any user in your database.
You probably need to set $username = $_SESSION['username']; in your second PHP script.

Unexpected catch error in code [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm doing registration in PHP and I am stuck on an unexpected catch, can you help me please?
if (isset($_POST['nick']) && isset($_POST['heslo']) &&
isset($_POST['email']) && isset($_POST['datnar']))
{
try
{
$email = ($_POST['email']);
$datnar = ($_POST['datnar']);
$nick = ($_POST['nick']);
$heslo = md5($_POST['heslo']);
$db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
echo "Registrace dokončena.";
catch( PDOException $Exception ) {
echo "Uživatel existuje";
}
}
You need to close the try block.
{
try
{
$email = ($_POST['email']);
$datnar = ($_POST['datnar']);
$nick = ($_POST['nick']);
$heslo = md5($_POST['heslo']);
$db->query("INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES ($nick, '$heslo', $email, $datnar)");
echo "Registrace dokončena.";
} //<-------------------------------------------- Here
catch(PDOException $Exception ) {
echo "Uživatel existuje";
}
}
Warning : Your code is vulnerable to SQL Injection. You need to filter the $_POST values before passing it to your query.
Use Prepared Statements (Parametrized Queries) to ward off SQL Injection attacks as you are already using PDO.
Add a closing curly bracket (}) before the catch
Here is how to fix your code
if (isset($_POST['nick']) && isset($_POST['heslo']) &&
isset($_POST['email']) && isset($_POST['datnar']))
{
$sql = "INSERT INTO tblosoba(`nick`, `heslo`, `email`, `datnar`) VALUES (?,?,?,?)";
$data = [$_POST['nick'],$_POST['heslo'],$_POST['email'],$_POST['datnar']];
$db->prepare($sql)->execute($data);
echo "Registrace dokončena.";
}
Note that you should not use try-catch here but should use prepared statement instead

i have an error while inserting the values what i did [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
help me with this code i am new to php
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$sql="INSERT INTO registration(fname,designation,emailid,
address,phonenumber)VALUES('".$_POST['fname']."','".$_POST['designation']."','".$_POST['ema
lid']."', '".$_POST['address']."','".$_POST['phonenumber']."')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
its a registration page getting values and inserting it in the table...
You have the parameters around the wrong way here:
$result=mysql_query($conn,$sql);
Try
$result=mysql_query($sql, $conn) or die(mysql_error($conn));
Side notes:
Don't use mysql_*() functions: they're deprecated. Use mysqli_*() versions instead.
You should escape your user inputs with mysql_real_escape_string() to protect against SQL Injection attacks. Consider using prepared statements with mysqli_() instead.
Take a look at this link which is a good tutorial for inserting data (from a form etc.) to a mysql database.
Also: be aware of sql-injection and prevent it. here is a tutorial on how to do this: link
If you want to have readable code, set the $_POST[] values to a variable, and then pass them to the query, it's not different in fact but this is more easy and clean.:
<?php
$conn=mysql_connect("localhost","root","","test");
if(isset($_POST['submit']))
{
$fname = $_POST['fname'];
$designation = $_POST['designation'];
$emailid = $_POST['emailid'];
$address = $_POST['address'];
$phonenumber = $_POST['phonenumber'];
$sql="INSERT INTO registration(fname,designation,emailid,address,phonenumber)";
$sql .="VALUES('$fname', '$designation', '$emailid', '$address', '$phonenumber')";
echo $sql;
$result=mysql_query($conn,$sql);
echo $result;
}
else{
echo "Error";
}
?>
you hade a typing mistake in $_POST['emailid']...
and you can select your database with this:
mysql_select_db('your db name');
put this line after your connection variable means $conn
and this is wrong:
$result = mysql_query ($conn, $sql)
you have to set the query first:
$result = mysql_query($sql, $conn)

Categories