Script to create a table and fields in SQL wont work - php

Warning this is lenghty! attack if you knowledagble. well at least more then a newb beginner like me.
This script uses three files as detailed below. It is suppoed to create the database and fields from the form input. It gets to the end and shows my_contacts has been created!. But when i go into phpMyadmin the table has not been created.
I have a file named show_createtable.html which is used to create a table in MySQL
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1>Step 1: Name and Number</h1>
<form method="post" action="do_showfielddef.php" />
<p><strong>Table Name:</strong><br />
<input type="text" name="table_name" size="30" /></p>
<p><strong>Number of fields:</strong><br />
<input type="text" name="num_fields" size="30" /></p>
<p><input type="submit" name="submit" value="go to step2" /></p>
</form>
</body>
</html>
This Form Posts to do_showfielddef.php
<?php
//validate important input
if ((!$_POST[table_name]) || (!$_POST[num_fields])) {
header( "location: show_createtable.html");
exit;
}
//begin creating form for display
$form_block = "
<form action=\"do_createtable.php\" method=\"post\">
<input name=\"table_name\" type=\"hidden\" value=\"$_POST[table_name]\">
<table cellspacing=\"5\" cellpadding=\"5\">
<tr>
<th>Field Name</th><th>Field Type</th><th>Table Length</th><th>Primary Key?</th><th>Auto-Increment?</th>
</tr>";
//count from 0 until you reach the number fo fields
for ($i = 0; $i <$_POST[num_fields]; $i++) {
$form_block .="
<tr>
<td align=center><input type=\"texr\" name=\"field name[]\"
size=\"30\"></td>
<td align=center>
<select name=\"field_type[]\">
<option value=\"char\">char</option>
<option value=\"date\">date</option>
<option value=\"float\">float</option>
<option value=\"int\">int</option>
<option value=\"text\">text</option>
<option value=\"varchar\">varchar</option>
</select>
</td>
<td align=center><input type=\"text\" name=\"field_length[]\" size=\"5\"></td>
<td aligh=center><input type=\"checkbox\" name=\"primary[]\" value=\"Y\"></td>
<td aligh=center><input type=\"checkbox\" name=\"auto_increment[]\" value=\"Y\"></td>
</tr>";
}
//finish up the form
$form_block .= "
<tr>
<td align=center colspan=3><input type =\"submit\" value=\"create table\">
</td>
</tr>
</table>
</form>";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create a database table: Step 2</title>
</head>
<body>
<h1>defnie fields for <? echo "$_POST[table_name]"; ?>
</h1>
<? echo "$form_block"; ?>
</body>
</html>
Which in turn creates the table and fields with this file do_showfielddef.php
//connect to database
$connection = #mysql_connect("localhost", "user", "pass")
or die(mysql_error());
$db = #mysql_select_db($db_name, $connection)
or die(mysql_error());
//start creating the SQL statement
$sql = "CREATE TABLE $_POST[table_name](";
//continue the SQL statement for each new field
for ($i = 0; $i < count($_POST[field_name]); $i++) {
$sql .= $_POST[field_name][$i]." ".$_POST[field_type][$i];
if ($_POST[auto_increment][$i] =="Y") {
$additional = "NOT NULL auto_increment";
} else {
$additional = "";
}
if ($_POST[primary][$i] =="Y") {
$additional .= ", primary key (".$_POST[field_name][$i].")";
} else {
$additional = "";
}
if ($_POST[field_length][$i] !="") {
$sql .= " (".$_POST[field_length][$i].") $additional ,";
} else {
$sql .=" $additional ,";
}
}
//clean up the end of the string
$sql = substr($sql, 0, -1);
$sql .= ")";
//execute the query
$result = mysql_query($sql, $connection) or die(mysql_error());
//get a giid message for display upon success
if ($result) {
$msg = "<p>" .$_POST[table_name]." has been created!</p>";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create A Database Table: Step 3</title>
</head>
<body>
<h1>Adding table to <? echo "$db_name"; ?>...</h1>
<? echo "$msg"; ?>
</body>
</html>

I cant believe I went to all the trouble of wrinting this Question. I had another good look at the phpMYAdmin and it had worked. The table had been created under a database called testDB which I assumed had nothing it in.
How did the script decided to etner this as a child under the testDB database?
Once again thanks everyone for your input, This site is truely amazine and is so valuable for a beginner like my self.

Related

Creating html input fields out of SQL SELECT statement

I'm extracting data from a database with a SELECT statement.
I would like to put this data into something, which you can write in (and later put a button save, which uses a SQL statement to rewrite the rows data).
The current code is:
index.php with login logic
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="logik.php" method="POST">
Username: <input type="text" name="uname" />
Password: <input type="password" name="pwd" />
DB-Name: <input type="text" name="dbname" value="unternehmendb" />
<input type="submit" />
</body>
</html>
After the login the SQL logic:
logik.php
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" type="text/css" href="grafik.css">
<title>unternehmendb</title>
</head>
<body>
<h1>Mitarbeiter</h1>
</body>
</html>
<?php
//test2
$servername = "localhost";
$username = $_POST['uname'];
$pass = $_POST['pwd'];
$dbname = $_POST['dbname'];
// Create connection
$link = new mysqli($servername, $username, $pass, $dbname);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "<table>";
$sql = "SELECT * FROM mitarbeiter";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Vorname"]. "</td><td> " . $row["Strasse"]. "</td><td>" . $row["Position"] . "</td><td>" . $row["id"] . " </td></tr> ";
}
} else {
echo "0 results";
}
echo "</table>";
mysqli_close($link);
?>
You're on track but instead of echoing result in td only, you can add text input fields making the values for the name attribute an array since you're getting multiple rows.
Everything within this
if($result->num_rows > 0)
block should be changed to:
if ($result->num_rows > 0)
{
//output data of each row
while($row = $result->fetch_assoc())
{
echo "<tr>
<td><input type='text' name='Name[]' value='".$row['Name']."' />
</td>
<td><input type='text' name='Vorname[]'
value='".$row['Vorname']."' /> </td>
<td><input type='text' name='Strasse[]'
value='".$row['Strasse']."' /> </td>
<td><input type='text' name='Position[]' value='".
$row['Position']."' /> </td>
<td><input type='text' name='id[]' value='".$row['id']."' />
</td>
</tr> ";
} //while()
?>
<tr> <td colspan="5"><center> <input type="submit" value="Save Data" />
</center></td></tr>
<?php
}// if result rows > 0
?>
Notice that after the loop, we created an additional row to house the
submit button.
Assuming there are no records, you could surround your statement in the else with since it will be printed within the tag as in:
echo "<tr> <td colspan='5'> No results Found </td> </tr>";
Hope this helps.

Empty query undefined variable when updating mysql Database

I'm trying to setup a form that can update my product.
the code reads data ok, but $update is getting errors that prevents the update from doing anything.
The errors are :
Undefined variable: update
mysqli::query(): Empty query (after submit the form)
Please Help! Thanks.
//include database configuration file
include("config.php");
$mysqli->set_charset("utf8");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Edit Page</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
$updateproductname = $_POST['updateproductname'];
$updatesku = $_POST['productsku'];
$updateproductoriginal = $_POST['updateoriginalname'];
$updatedescshort = $_POST['updatedescshort'];
$update = $mysqli->query("UPDATE testproducts".
"SET product_sku=$updatesku, product_name=$updateproductname, 'product_originalname'='$updateproductoriginal', 'product_description_short='$updatedescshort' ".
"WHERE product_id = '$id' ");
$mysqli->query($update) or die("Cannot update");//update or error
}
?>
<?php
//Create a query
$sql = "SELECT * FROM testproducts WHERE product_id = $id";
//submit the query and capture the result
$result = $mysqli->query($sql) or die(mysql_error());
?>
<h2>Update Record <?php echo $id;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {?>
<table border="0" cellspacing="10">
<tr>
<td>Product Name:</td> <td><input type="text" name="updateproductname" value="<?php echo $row['product_name']; ?>"></td>
</tr>
<tr>
<td>Product Original Name:</td> <td><input type="text" name="updateoriginalname" value="<?php echo $row['product_originalname']; ?>"></td>
</tr>
<tr>
<td>Product SKU:</td> <td><input type="text" name="productsku" value="<?php echo $row['product_sku']; ?>"></td>
</tr>
<tr>
<td>ShortDescription:</td> <td><input type="text" name="updatedescshort" size="100" value="<?php echo $row['product_description_short']; ?>"></td>
</tr>
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if($update){//if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
a) You are vulnerable to SQL injection attacks
b) Read the docs for mysqli_query(). The function takes a query STRING, and returns a RESULT HANDLE. You're then taking that result handle and trying to re-query it. If you'd bothered having proper error handling on ALL of your mysqli calls, you'd have seen this.
was able to update the record after moving the update and select code to top of html
<?php
if(isset($_POST['Submit'])){//if the submit button is clicked
// Check connection
$productname = $_POST['updateproductname'];
$productoriginal = $_POST['updateoriginalname'];
$sku = $_POST['productsku'];
$descshort = $_POST['updatedescshort'];
$mysqli->query("UPDATE testproducts ".
"SET product_name='$productname',product_originalname='$productoriginal', product_sku='$sku', product_description_short='$descshort'".
" WHERE product_id='$id'");
}
?>
<?php
//Create a query
$sql = "SELECT * FROM testproducts WHERE product_id = $id";
//submit the query and capture the result
$result = $mysqli->query($sql) or die(mysql_error());
//$query=getenv(QUERY_STRING);
//parse_str($query);
//$ud_title = $_POST['Title'];
//$ud_pub = $_POST['Publisher'];
//$ud_pubdate = $_POST['PublishDate'];
//$ud_img = $_POST['Image'];
$mysqli->close();
?>

Select box populated from database invisible text

My problem is not connecting my select box to my database but getting the info to show.... It connects and i can see the boxes for the amount of items i have in my database table but there is no text in any of them. My database table is .CSV im not sure if that could cause a problem?
Here is my code: In my code i will just put in dummy_.... (What ever item) instead of the real thing.
<?php
require_once('auth.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<link href="styles/stylesheet.css" rel="stylesheet" type="text/css">
<head>
</head>
<body>
<form id="dropdown">
<?php
mysql_connect("localhost", "repaiami_member", "zmozmozm2083") or die("Connection Failed");
mysql_select_db("repaiami_member")or die("Connection Failed");
?>
<?php
$query = "SELECT * FROM lighting";
$result = mysql_query($query);
?>
<table width="450px;">
<tr>
<td>
<select id="dropdown_description" name="select1" class="ui-select selBox">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['field'];?>"> <?php echo $line['field'];?></option>
<?php } ?>
</select>
</td>
<td>
<input type="text" name="first_name" maxlength="50" size="30">
</td>
</tr>
</table>
</form>
</body>
</html>
Can anyone help?

Need Help For This PHP Checkbox is Value Calculation Srcipts

Assalamu'alaikum, i am use this scripts for calculate the value of checkbox named "Biaya" and it is works.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<?php
mysql_connect("localhost", "root")or die("cannot connect");
mysql_select_db("spp")or die("cannot select DB");
$sql="SELECT `idtagihan`, `namatagihan`,`biaya` from tagihan";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table border=1>
<tr>
<td>
<form name="form1" method="post">
<table>
<tr>
<td>Id</td>
<td>Nama</td>
<td>Harga</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['idtagihan']; ?>></td>
<td><?php echo $rows['namatagihan']; ?></td>
<td>Rp. <?php echo $rows['biaya']; ?>,-</td>
<td><input type="checkbox" name=check[] value="<?php echo $rows['namatagihan']; ?>" data-weight="<?php echo $rows['biaya']; ?>"></td>
</tr>
<?php
}
?>
<tr>
<td colspan=3><input name="Next" type="submit" id="Next" value="Next"></td>
</tr>
<?php
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
<div>Total: <span id="total">0</span></div>
</body>
</html>
<script type="text/javascript">
(function () {
var totalEl = document.getElementById('total'),
total = 0,
checkboxes = document.form1['check[]'],
handleClick = function () {
total += parseInt(this.getAttribute('data-weight'), 10) * (this.checked ? 1 : -1);
totalEl.innerHTML = total;
},
i, l
;
for (i = 0, l = checkboxes.length; i < l; ++i) {
checkboxes[i].onclick = handleClick;
}
}());
</script>
The result is like this :
First result pic
Then i develop that code for updating it's value to database but it cannot calculate anymore. Here is the whole php code :
<?php
// Start session
session_start();
require_once('includes/functions.inc.php');
// Check login status... if not logged in, redirect to login screen
if (check_login_status() == false) {
redirect('login.php');
}
// Connection to the database
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="spp"; // Database name
$tbl_name="tagihan"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
if(isset($_POST['check'])){$checkbox = $_POST['check'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql2="UPDATE tagihan SET status = '".(isset($activate)?'Lunas':'Belum Lunas')."' WHERE idtagihan IN $id" ;
$result = mysql_query($sql2) or die(mysql_error());
}
$nim = $_SESSION['nim'];
$sql="SELECT `idtagihan`, `namatagihan`, `biaya` FROM tagihan WHERE nim='".$nim."' and status='Belum lunas' ";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8" />
<title>Pembayaran SPP</title>
<link rel="stylesheet" type="text/css" href="css/gaya.css" />
<link href="css/menu.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="halaman">
<h1>Pembayaran SPP</h1>
<p>Keluar
<?php
$nim = $_SESSION['nim'];
?>
<label>Nim anda : </label> <input type="total" name="nim" id="nim" readOnly="readonly" value="<?php echo $nim; ?>" >
</p>
</br>
<div class="tabel" >
<form name="frmactive" method="post" action="">
<table>
<tr>
<td>Id</td>
<td>Nama</td>
<td>Harga</td>
<td>Pilih</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $rows['idtagihan']; ?></td>
<td><?php echo $rows['namatagihan']; ?></td>
<td>Rp. <?php echo $rows['biaya']; ?>,-</td>
<td><input class="css-checkbox" type="checkbox" name='check[]' name='cek[]' value="<?php echo $rows['idtagihan']; ?>" biaya = "<?php echo $rows['biaya']; ?>"></td>
</tr>
<?php
}
?> </table>
<div class="tabelspp" >
<table>
<tr>
<td><label>Total Rp.</label><input type="total" id="total2" readOnly="readonly"></input><label>,-</label>
<input type="submit" name="activate" id="activate" value="Bayar" /> </td>
</tr>
</table> </form> </div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
(function () {
var totalEl = document.getElementById('total2'),
total2 = 0,
checkboxes = document.form1['check[]'],
handleClick = function () {
total2 += parseInt(this.getAttribute('biaya'), 10) * (this.checked ? 1 : -1);
totalEl.value = total2;
},
i, l
;
for (i = 0, l = checkboxes.length; i < l; ++i) {
checkboxes[i].onclick = handleClick;
}
}());
</script>
Then here is the result :
Second result pic
I can update the database successfully. But my question is how to make that second script can calculate the value's checkbox again same as first script? I need to resolve this, i hope there someone who can answer this. I am happy if there anyone reply my post. Thank you.
for first, try to change the name of the form
from
<form name="frmactive" method="post" action="">
to this
<form method="post" action="" name="form1">

Getting dependant data from two tables

I'm trying to create a page which uses session data to find a user in a database and then sends the events that this user has signed up to. I'm a bit of a newbie and have got very confused with where I am at. I am using two different tables to get the data, and this is where I'm getting confused and where I believe the errors are occurring. Thanks in Advance.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<?php
$username = $_SESSION['username'];
$email = $_SESSION['user_email'];
$con=mysqli_connect("localhost","emuas","******","EMUAS_signUp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo "<table>
<tr>
<td> Logged in as:</td>
</tr>
<tr>
<th>" . $username . "</th>
</tr>
<tr>
<td>
<form action='logout.php' method='post'>
<input type='submit' value='Logout' >
</form>
</td>
</tr>
<tr>
<th>Events Attending:</th>
</tr>";
$find = mysqli_query($con,"SELECT * FROM SIGN_UP_TEST WHERE User = '$username'");
while($find_row = mysqli_fetch_array($find)){
//Get Event ID
$eventId = $find_row['EventID'];
//Use Event ID to get Event Name
$result = mysqli_query($con,"SELECT * TEST WHERE EventID = '$eventId'");
//Insert Event Name into table with link from Page Name
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> <a href='http://www.emuas.co.uk/members/sign_up_sheets/S" . $row['PageName'] . ".php'>" . $row["EventName"] . "</a> </td>";
echo "</tr>";
}
}
echo "</table>";
?>
<body>
</body>
</html>

Categories