I have 2 tables, one with data and other is blank in same database.
a)- Tables "cusrec" is main and contains data in it.
b)- Tables "order" is empty and I want to insert the data in it.
I tried to fetch data from table "cusrec" and insert it into "order", when I echo, it shows the data of table "cusrec" but it is not inserting into table "order". Both tables are in same database.
Code is:
<?php
mysql_connect("localhost","root","");
mysql_select_db('dobhighat');
if(isset($_GET['search'])){
$srch = $_GET['srch'];
$que=mysql_query("select * from cusrec where custid='$srch' OR mobile='$srch'");
$ftch=mysql_fetch_array($que);
$scustid=$ftch['custid'];
$sname=$ftch['name'];
$smobile=$ftch['mobile'];
$totcloth=$ftch['clothpackage'];
if(isset($_POST['confirm']))
{
$ordernum=$_REQUEST['ordernum'];
$orderdate=date('d/m/y');
$ordercloth=$_REQUEST['ordercloth'];
$clothrem=$totcloth-$ordercloth;
$abc=mysql_query("insert into order(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
}
}
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<?php $orddate=date('d/m/y'); ?>
<form name="form 1" action="" method="get">
<div align="right"><input type="text" name="srch" placeholder="Search by Id or Mobile" size="25">
<input type="submit" name="search" value="Search"></div>
</form>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Order Date</td>
<td width="94">Customer Id</td>
<td width="53">Name</td>
<td width="71">Mobile</td>
<td width="144">Order No.</td>
<td width="144">No.of Clothes</td>
</tr>
<tr>
<td><?php echo $orddate; ?></td>
<td><?php echo #$ftch['custid']; ?></td>
<td><?php echo #$ftch['name']; ?></td>
<td><?php echo #$ftch['lname']; ?></td>
<td><?php echo #$ftch['mobile']; ?></td>
<td><input type="text" name="ordernum" required></td>
<td><input type="text" name="ordercloth" required></td>
</tr>
<tr><td colspan="8"><center><input type="submit" name="confirm" value="Confirm"></center></td></tr>
</table>
</form>
</body>
</html>
Help is needed
Forget all I said about the forms and the structure of the document (although it could be useful eventually as I don't know how reliable is that GET and POST).
I am a dodo and just realized that your table name is order. ORDER is a reserved keyword in SQL and it's the reason why your SQL statement is incorrect! Just put the name between ` and it will work:
$abc=mysql_query("insert into `order`(custid,name,mobile,totcloth,orderno,orderdate,ordercloth,clothrem)values('$scustid','$sname','$smobile','$totcloth','$ordernum','$orderdate','$ordercloth','$clothrem')");
Or you may want (if possible) to rename the table in order to avoid confusion and future problems.
This doesn't mean that the code is perfect. You should still look at the recommendations by the other users and the list below, and improve it. Specially the security concerns.
Once you fix that, the insert will work; but there are still many things that you need to fix:
You should not use mysql functions and move to mysqli or PDO.
You should sanitize all the values that go to the database or to the page:
Your code is subject to SQL injection (see comments in question).
Your code is subject to XSS (see comments in question).
The doctype in your page is incorrect (if you want html5, it should be <!doctype html> and not <!doctype>.
Names and IDs must not have white spaces in them (read this for name and id notation: http://www.w3.org/TR/html401/types.html#type-name)
As stated in other answers, the SQL statement could be improved. The solution that you have may work fine (I don't find any apparent error) but it is not ideal and may present performance problems and other type of problems (e.g.: if two different users have the same phone number).
And there are probably more things that I didn't notice as I just looked quickly through the code.
Have you thought of doing an insert from select? Something like...
INSERT INTO ORDER
( custid, name, mobile, otherFields, etc... )
SELECT same, ordered, fields, as, theInsert
from custrec where custid='$srch' OR mobile='$srch'
The only issue I see with your select where clause is that you could be getting multiple customers via the OR mobile='%srch' and cause duplicate orders.
You can do it directly from SQL
INSERT INTO order
( custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem)
SELECT
custid,
name,
mobile,
totcloth,
orderno,
orderdate,
ordercloth,
clothrem
FROM cusrec
WHERE custid='$srch' OR mobile='$srch'"
;
You just need to match the column with from table to to table
I think to insert and fetch the same data we can do it by using the below-mentioned code for PHP MYSQLI.
$id=trim($_POST['id']);
$email=trim($_POST['email'];
$env_name=trim($_POST['env_name'];
$sql="INSERT INTO integration (id,email,env_name) VALUES ($id,$email'$envName')";
if(mysqli_query($conn,$sql)){
$selectSql="SELECT id,email,env_name from integration WHERE id=$id and email='$email'";
$result=mysqli_query($conn,$selectSql){
if($result){
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
return $row;
}
}
}
Related
my question is, how could I insert data from a table with the click of a button into mysql DB?
The table on my HTML is as follows:
<table>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
</table>
The rows of course continue, depending on the data inserted.
In my DB, the tables are as follows:
Person (ID, Name, Number)
The number table in the DB is blank, while the Name and ID tables are already filled up with data.
I have a global variable where the number of total people is stored, which I think can come in handy
var totalPeople
As I mentioned before, I would like to make an ajax request and send the "Number" data from the HTML table into the Number column inside my DB, matching the name each person has (So, if for example, on my HTML table I have "David" with number 3 and "James" with number 5, I want the button to insert 3 into the David row in my DB and 5 into the James row).
I thought of creating an array from the table and sending that array through ajax and making the SQL query, but I'm quite stuck as to how to do this...
Thanks in advance
Well, here is how you should do, in my opinon:
persons_table.php: the page where you display your data table with hidden inputs with persons ids, example (use loops of course):
<form method="post" action="save_persons.php">
<table>
[headers...]
<tr>
<td><input type="hidden" name="id[]" value="<?= $id ?>" /> John</td>
<td><input type="text" name="number[]" value="<?= $number ?>" /> </td>
</tr>
</table>
[submit button...]
</form>
save_persons.php: the page which gonna be requested, you can loop on $_POST (I suppose you're doing this way) and UPDATE your rows like this:
UPDATE Person SET number = $number WHERE id = $id;
I would suggest you to have a look at PDO, prepared statements and Model View Controller design pattern.
Regards.
I seem to have an issue inserting the post values into my database, and i don't see the error in the coding. I've been looking at it for a while now and to me everything looks right, however when i use the form and submit the data the page reload but no data get inserted into the database.
It would be much appreciated if someone could help me identify the error in the coding.
If you have any questions feel free to ask!
Kind regards Jim
FORM
<?php
//Show the form if the user is a Admin
if(isset($_SESSION['username'])){
$username == $_SESSION['username'];
$results = $mysqli->query("SELECT authority FROM users WHERE username='$username' LIMIT 1");
while($row = $results->fetch_object()){
$aut = $row->authority;
}
}
if($aut == 1){
?>
<form action="index.php" method="post">
<table>
<tr>
<td> Title: </td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td valign="top"> News: </td>
<td><textarea name="information"></textarea></td>
</tr>
<tr>
<td> <input type="hidden" value="news"> </td>
<td><input type="submit"></td>
</tr>
</table> <hr>
</form>
MYSQLI
<?php
}
//Insert into the database
if(isset($_POST['news'])){
$title = $_POST['title'];
$information = $_POST['information'];
$mysqli->query("INSERT INTO `news` (`title`, `information`) VALUES ( '".$title."', '".$information."')");
}
<input type="hidden" value="news"> should be <input type="hidden" name="news">
That's why isset($_POST['news']) will never be true.
Beside that silly typo problem your code suffers from two real disasters.
You have no error reporting, which renders you helpless against such silly mistakes
You are adding your data directly into query, while ought to use placeholders for that.
I am not sure what was intended with the backticks and periods in your original query. In my limited experience my queries take the form of:
$mysqli->query("INSERT INTO news(title, information) VALUES ('$title', '$information')");
I would say that priority #1 is getting some debugging information in the form of return values for your php functions or access to php error logs.
I have a table with php values (table.php )retrieve from mysql database.
I want to insert this particular value into another database with the insertion code inside another php file (admin.php)
How should I go about doing it?
Code from table.php
<tr>
<td class="brack_under cell_1">
<?php
$row = mysql_fetch_row($data);
echo "<a>".$row[2]."</a>";
?>
</td>
<td class="cell_2"> </td>
<td class="cell_3"> </td>
<td class="cell_4"> </td>
<td class="cell_5"> </td>
<td class="cell_6"> </td>
</tr>
Code from admin.php
<?php
it is something like : $a = $_POST[ $row[2] ]; ???
$sql="INSERT INTO matchTable (schInitial, schName,position)VALUES
('$_POST[ $row[1] ]','$_POST[$row[2] ]','top8')";
mysql_close($con)
?>
According to the comment discussion and your comments, I'm gonna try to help you a bit here (hopefully I got the point)
You need to POST a <form ...> to your script. Unless you do that, there is no $_POST available. E.g.:
<form method="post" action="myscript.php">
<input type="hidden" name="some_var" value="player1" />
<input type="submit" />
</form>
This gives the following in myscript.php where you can do your filtering and insertion and stuff.
print_r($_POST);
// output: array( 'some_var' => 'player1' );
Which means, according to your tries (and to keep it understandable)
$a = $_POST['some_var']
// $a is now 'player1'
So, the only thing you need to do: create a form beneath your table, put some hidden fields in it with data you need to do your math things, and put a submit button in it.
I am new to PhP and MySQL and now having trouble displaying certain records. I have records pf list of students and their year level stored in a database. I was able to display all of them in a webpage. Now I have one textbox and a button and what I wanted to do is when I enter for example "1" on the textbox and click the button, what will appear on my page will be the records of all the first year students only.
Somehow I need to change it so that when the year is posted back then it changes the sql to limit the information displayed.
Any suggestions or links to some examples will be much appreciated. Here is my code.
<form name="form1" method="post" action="">
<div align="center">
<?php
include("dbcon.php");
$query="select * from student order by year, studname";
$result=#mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result)>0)
{
?>
<label>
<input type="text" name="txtyear" id="txtyear">
<input type="submit" name="btnyear" id="btnyear" value="Submit">
</label>
<table width="75%" border="1">
<tr>
<td align="center" width="20%"><strong>Student Number</strong></td>
<td align="center" width="27%"><strong>Name</strong></td>
<td align="center" width="23%"><strong>Course</strong></td>
<td align="center" width="30%"><strong>Year Level</strong></td>
</tr>
<?php
while($row=mysql_fetch_array($result))
{echo "<tr>";
echo "<td>".$row['studno']."</td>";
echo "<td>".$row['studname']."</td>";
echo "<td>".$row['course']."</td>";
echo "<td>".$row['year']."</td>";
echo "</tr>";
}
?>
</table>
<?php
}
else
echo "no records found";
?>
</div>
</form>
You need a WHERE clause. A very basic example might look like this:
$year = mysql_real_escape_string($_POST['year']);
$query = SELECT * FROM student WHERE year = $year ORDER BY studname";
NB: Look into the PHP MySQLi extension. These functions are almost identical to their mysql equivalent, but come with numerous improvements.
Also, you would likely want to improve the validation of the $_POST['year'] field. Ensuring that it is an integer with is_int() wouldn't be a bad idea. You could also typecast it with (int) like (int) $year = mysql_real_escape_string($_POST['year']); and then perform the query if the year isn't 0. Perhaps you know all this already... or perhaps I'm getting ahead of myself. Either way, I'll stop. :)
You can find more info about Mysql select query syntax on
http://dev.mysql.com/doc/refman/5.1/en/select.html.
Also don't use # for errors suppression in php-code. Because of it will slow your script. Try to process such situation manually. In this case (#mysql_query($query)) it seems it doesn't make sense anyway.
I have a small section of code. When the table is empty this code works fine and enters in to the table fine. But then if i try again then this fails with the error?
What am i doing wrong?
Thanks
// On my Function page
function admin(){
connect();
$query = mysql_query("INSERT INTO results
(t_id, pos1, pos2, pos3)
VALUES ('$_POST[t_id]','$_POST[pos1]','$_POST[pos2]','$_POST[pos3]')")
or die ("Error.");
$b = "Updated fine</b></a>.";
return $b;
exit();
}
// Then on my main page
<?php
include ('functions.php');
if (isset($_POST['admin'])){
$admin = admin();
}
?>
<div id="content">
<div id="admin">
<form action="" method="post">
<table width="100%" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td width="100%"><?php echo "$admin"; ?></td>
</tr>
<tr>
<td width="100%"><label>Track <input type="text" name="track" size="25" value="<? echo $_POST[t_id]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 1<input type="text" name="pos1" size="25" value="<? echo $_POST[pos1]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 2 <input type="text" name="pos2" size="25" value="<? echo $_POST[pos2]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><label>Position 3 <input type="text" name="pos3" size="25" value="<? echo $_POST[pos3]; ?>"></label></td>
</tr>
<tr>
<td width="100%"><input class="save" type="submit" value="" name="admin"></td>
</tr>
</table>
</form>
</div>
</div>
Without seeing your table schema, I can only think you have UNIQUE t_id and you want to insert the same ID into it.
Several way to debug:
Use or die ("Error: " . mysql_error()); instead of just or die ("Error.");
Check your table schema: SHOW CREATE TABLE tablename and write it down on your question, so we can see if it's causing error.
It is hard to guess. Maybe you are entering the same values twice, and they happen to violate some unique constraint?
But you make another mistake: you forget to call mysql_real_escape(). That is bad.
Can you tell us of the error? It sounds like you're hitting a primary key violation, perhaps by trying to insert the same id more than once.
That aside, your code is riddled with security holes.
You should not be inserting variables straight from the POST into your query. All I have to do is submit '; DROP DATABASE and I can completely wreck your system.
Additionally, you're injecting values directly from POST into input fields, meaning I can set up a button on my site that submits " <script type='text/javascript'>window.location='http://mysite.com'</script> or something along those lines and take over your page.
This may sound terse, but you should do some googling or pick up a book regarding textbook security issues with websites.
EDIT: Just saw your comment about learning security. My advice is to be proactive about this sort of thing, because being reactive is often too late to fix problems.