Insert array data using php - php

I am using form to insert data into SQL.
This is my form:
<form action="insert.php" method="POST">
Name:<input type="text" name="firstname[]" />
</form>
and this is my PHP code:
<?php
$con = mysql_connect("localhost", "root", "root");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
while ($array = $result->fetch_assoc()) {
$query = "INSERT INTO test(firstname) VALUES ('{$array['firstname']}')";
$result = $database->query($query);
}
mysql_close($con);
?>
It shows an error. Any help?

To insert POST data in a table, you don't have to first fetch it from database (* this would not exist). So remove some extra code:
<?php
$con = mysql_connect("localhost","root","root");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$first_name = mysql_real_escape_string($_POST["firstname"]);
$query = "INSERT INTO test (firstname) VALUES ('$first_name')";
$result = mysql_query($query);
mysql_close($con);
?>
And update your HTML so that the field is named firstname and not firstname[].
Edit: mysql_* functions are not really recommended to be used anymore. But I had to answer within your question's requirements.

Related

mysql api submite towice

I tried many times to submit the form when it submitted it repeated the submission twice on the data. I don't understand why,please help me. and when I put the header location it doesn't work ever
here is the code
<?php
$name= $_POST['form_name'];
$mrn= $_POST['form_mrn'];
$mobile= $_POST['form_mobile'];
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('dbname');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
mysql_set_charset('utf8',$link);
$query = "INSERT INTO pharmacy ( name , mrn , mobile ) VALUES ('$name', '$mrn', '$mobile')";
$result = mysql_query($query);
header('Location: form.html');
$link->close();
?>
<?php
$name= $_POST['form_name'];
$mrn= $_POST['form_mrn'];
$mobile= $_POST['form_mobile'];
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('dbname');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
mysql_set_charset('utf8',$link);
//Just Put this code before inserting
if($name !=""){
$query = "INSERT INTO pharmacy ( name , mrn , mobile ) VALUES ('$name','$mrn', '$mobile')";
$result = mysql_query($query);
header('Location: form.html');
}
$link->close();
?>
Just check condition before insert. Let me know if facing same issue.

Compare PHP Variable value with MySQL Column value

I receive a post and want to do some actions only if the value of variable received in post exists in a specific column of the table. So i did this:
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "pedidoID"');
if(mysql_num_rows($result) == 0) {
//Some actions
}
So if the value from pedidoID doesn't exist in the column numeroPedido it will do the actions, because result will be 0 (because no rows are found).
What is happenning is that the $result is returning as bool(false) in both cases (if the value exists or not). I guess that my problem is how I'm using the variable inside the SELECT to compare to the column. I've tried to insert $_POST["pedidoID"] inside the SELECT also but my syntax was also wrong.
Does anyone know the correct syntax to use?
Try:
$pedidoID = mysql_real_escape_string($_POST["pedidoID"]);
$con = mysql_connect("127.0.0.1", "root", "password") or die("Could not connect: " . mysql_error());
mysql_select_db('<your_database_name>', $con);
$result = mysql_query("SELECT id FROM listapagamento WHERE numeroPedido = 'pedidoID'");
if(mysql_num_rows($result) == 0) {
//Some actions
}
When you write code that deal with database, make always sure that it's not vulnerable to sql injection. Now for your case, you have to treat the post element before using it:
$pedidoID = mysql_real_escape_string ($_POST["pedidoID"]);
Then for your bug, you haven't select the database:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Connection to Mysql failed : ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
if (!$db_selected) {
die ('connection to database failed : ' .mysql_error());
}
$result = mysql_query("SELECT id FROM listapagamento WHERE numeroPedido=$pedidoID");
Right now you are comparing the column's value with a fixed string, hence your error. Put the variable in the code instead.
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "Password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "' . $pedidoID . '"');
if(mysql_num_rows($result) == 0) {
//Some actions
}
HOWEVER this code is wide open to SQL injection attacks, you should always sanitize any input before using it. Which, as recommended, would look like:
$pedidoID = $_POST["pedidoID"];
$con = mysql_connect("127.0.0.1", "root", "Password") or die("Could not connect: " . mysql_error());
$result = mysql_query('SELECT id FROM listapagamento WHERE numeroPedido = "' . mysqli_real_escape_string($pedidoID) . '"');
if(mysql_num_rows($result) == 0) {
//Some actions
}

Getting php variable to select statement not working

Here i am trying to pass the variable to php select query,but its not working.
couldn't figure out what is the problem.
code:
<?php
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM co_details where co_name="$cname"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<br>";
echo "Course Details <br>";
echo $row['co_name']."<br>";
echo $row['co_objectives']."<br>";
echo $row['co_outline']."<br>";
echo $row['co_prereq']."<br>";
echo $row['co_fee']."<br>";
echo $row['co_duration']."<br>";
}
mysqli_close($conn);
}
?>
what may be the reason?
Instead of variable $cname if i put the direct value then the query is executing successfully.
Note that single quoted strings like this one you have:
$sql = 'SELECT * FROM co_details where co_name="$cname"';
That variable that you think you have there will not get interpolated. It will only work by using double quoted strings.
$sql = "SELECT * FROM co_details where co_name='$cname'";
And as #Fred has said in the comments, stick with MySQLi including your connection error:
if(! $conn )
{
die('Could not connect: ' . mysql_error()); // mysql API doesn't belong
}
Change it to MySQLi interface:
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
And you should have used prepared statements instead as this is prone to SQL injection.
<?php
if(!empty($_GET['c_name'])) {
$cname = $_GET['c_name'];
include 'config.php';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_errno) {
die('Could not connect: ' . $conn->connect_error);
}
$sql = 'SELECT co_name, co_objectives, co_outline, co_prereq, co_fee, co_duration FROM co_details WHERE co_name = ?';
$select = $conn->prepare($sql);
$select->bind_param('s', $cname);
$select->execute();
$select->store_result();
$select->bind_result($co_name, $co_objectives, $co_outline, $co_prereq, $co_fee, $co_duration);
while($select->fetch()) {
echo "<br/>
Course Details: <br/>
$co_name <br/>
$co_objectives <br/>
$co_outline <br/>
$co_prereq <br/>
$co_fee <br/>
$co_duration <hr/>
";
}
}
?>
You can't use $cname directly in the string: try as shown below:
$sql = "SELECT * FROM co_details where co_name='".$cname."'";
Hope, it helps!
You are using single quote don't do like that change the query like this
$sql = "SELECT * FROM co_details where co_name='$cname'";

MySQL won't update with URL variable

I'm having troubles getting my code to work properly. If I type it into phpMyAdmin it works, but when I try it in the code, it doesn't update the database.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
mysql_close($con);
?>
Try out this code snippet and see how you get on.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($query);
mysql_close($con);
}
?>
I would recommend doing it this way as mysql is no longer supported by PHP.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if (!$mysqli) {
die('Could not connect: ' . $mysqli->connect_error);
} else {
$sp = $mysqli->real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$mysqli->query(query);
$mysqli->close();
}
?>
You're not EXECUTING your query. You're just defining a string that happens to contain some SQL, e.g.
$sql = "blah blah blah";
$result = mysql_query($sql) or die(mysql_error()); <--forgot this
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$sql = "UPDATE TRACKDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($sql) or die(mysql_error());
mysql_close($con);
?>

Deleting row from a MySQL Table using checkboxes and a button

I want to make a table with the members of a website and in this table when you check the checkboxes and you press the "Delete" button to delete this member from the members table and also to delete his applications from the applications table. With my code when I click the delete button it prints me "Query failed"
This is my code:
<?php
require_once('config.php');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$data = mysql_query("SELECT * FROM members ") or die(mysql_error());
echo ' <form action="members-exec.php">
<table width="760" border=1>
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<th></th>';
}
echo '
<th>Служител:</th>
<th>Отпуск отпреди 2009год.</th>
<th>Отпуск от мин. год.</th>
<th>Отпуск от тек. год.</th>
</tr>';
while($info = mysql_fetch_array( $data ))
{
echo '
<tr>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<td>
<input type="checkbox" name="'.$info['firstname'] .' '.$info['lastname'] .'" value="'.$info['firstname'] .' '.$info['lastname'] .'" />
</td>';
}
echo '
<td>'.$info['firstname'] .' '.$info['lastname'] .'</td>
<td>'.$info['predi'] .'</td>
<td>'.$info['minali'] .'</td>
<td>'.$info['tekushti'] .'</td>';
}
echo' </tr> ';
echo '</table>';
if(isset($_SESSION['SESS_RANK'])) {
echo '
<br> <input type="submit" name="remove" value="Delete" /></form>';
}
?>
This is my php part:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" && "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
EDIT:
<?php
session_start();
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'" ;
$result = mysql_query($qry);
$qry = "DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
if($result) {
header("location: members.php");
exit();
}else {
die("Query failed");
}
?>
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"
&& "DELETE FROM applications WHERE userfname = '$userfname'";
There's your problem - you're trying to do two SQL statements with one call, and mysql_query won't let you do that. It should work if you do two separate queries.
HOWEVER
You should look at moving to mysqli_* or PDO - mysql_* is being deprecated. You can do multiple queries in one call directly using mysqli, too; and they both make use of bound parameters, which helps you write more secure code.
You are trying to execute two delete statements in one query. This is a no-no.
You will need to split the statements into two executes:
$qry = "DELETE FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'";
$result = mysql_query($qry);
$qry="DELETE FROM applications WHERE userfname = '$userfname'";
$result = mysql_query($qry);
You can always try and use mysqli_multi_query()

Categories