Forum Moderators: coopster

Message Too Old, No Replies

Retrieve and update mysql data from .php file

mysql php

         

fulanitok

9:40 pm on Jan 28, 2012 (gmt 0)

10+ Year Member



Hi everyone,

I'm webmaster of a little Baseball team in Ghent (Belgium) and new to php language, I use to play with Actionscrip. I have a database (mysql) where all members info is stored.

I'm trying make a kind of 'editable' php FORM to retrieve mysql data and write it back to mysql. At this moment I've learn how to retrieve the data from mysql in a non-editable php file. BTW it fun to play with php script.

Retrieve data from database script in non-editable php file, this may help some newbees like me:

Connect to database code connect.php

<?php
DEFINE ('DB_USER', 'username');
DEFINE ('DB_PSWD', 'password');
DEFINE ('DB_HOST', 'localhost);
DEFINE ('DB_NAME', 'databaseName');
$condb = mysqli_connect(DB_HOST, DB_USER,DB_PSWD,DB_NAME);
?>


Retrive code search.php

<html>
<head>
<title>pageName</title>
<style type="text/css">
table {
background-color: #ADD8E6;
border: 1px solid black;
font-family: Arial; font-size: 14px;
}
th {
text-align: left;
}
</style>
</head>
<body>
<h1>MEMBERS SEARCH</h1>
<form method="post" action="search.php">
<input type="hidden" name="submitted" value="true"/>
<label> Search Category:
<select name="category">
<option value="first">First NAME</option>
<option value="last">Last NAME</option>
<option value="licencenr">Licence</option>
</select>
</label>
<label> Search Criteria:<input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
// connect to the DB
include('connect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM members WHERE $category LIKE '%".$criteria."%'";
$result = mysqli_query ($condb, $query) or die ('error getting data from database');
$num_rows = mysqli_num_rows ($result);
echo "$num_rows results found";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
?>
<table>
<tr>
<td width="300" ><font face="Arial Black" size="2"><?php echo $row['last']?> <?php echo $row['first']?></font></td>
</tr>
</table>
<table>
<tr>
<td width="100"><b>Licence #</b></td>
<td width="3">:</td>
<td width="120"><?php echo $row['licencenr']?></td>
</tr>
<tr>
<td width="100"><b>Birthday</b></td>
<td width="3">:</td>
<td width="120"><?php echo $row['birth']?></td>
</tr>
<tr>
<td width="100"><b>Age</b></td>
<td width="3">:</td>
<td width="120"><?php echo $row['age']?></td>
</tr>
<td width="120"> </td>
</tr>
</table>
<br>
<?php
}
}
?>
</body>
</html>


Searching in the internet I found this forum, I've also found a php script that might be what I'm looking for but I'm blocked, data is retrieved, the editable form shows up but don't get the data writed bask to my database. Get an ERROR: Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3

Here the code:

RETRIEVE page: displayData.php

<form method="get">
<?php
//connects to database
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("databaseName", $con);

//retrieve data from database
$result = mysql_query("SELECT * FROM tableName");

Print "<table border cellpadding=3>";
while($row = mysql_fetch_array($result))
{
Print "<tr>";
Print "<td>" . $row['licencenr'] . "</td>";
Print "<td>" . $row['first'] . "</td>";
Print "<td>" . $row['mobile'] . "</td>";
Print "<td>" . $row['brith'] . "</td>";
Print "<td>" . "<a href='editData.php?action=edit&id=" . $row['licencenr'] . "'>Edit</a>" . "</td>";

Print "</tr>";
}
echo "</table>";

?>
</form>


Now the editData.php script:


<input type="hidden" name="ID" value="<? echo "$ID" ?>">

<html><head><title></title></head>
<body>
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("databaseName", $con);

if (isset($_GET["abc"]))
{
$ID=$_POST['licencenr'];
$Name = $_POST['first'];
$Telephone = $_POST['mobile'];
$Birthday = $_POST['birth'];

//Update database

$sql="UPDATE tableName
SET Name='$Name', Telephone='$Telephone', Birthday='$Birthday'
WHERE ID = $ID";
$result = mysql_db_query($db, $sql, $con);

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else {
echo "Updated successfully!";
}
//trying to mk the data appear into my textbox
//mysql_close($con);
}
?>

<?php
$query = mysql_query ("SELECT * from members WHERE ID = $ID");
?>

<table width="300" cellpadding="3" cellspacing="0" border="2">
<tr align="center" valign="top">
<td colspan="1" rowspan="1" align="center">
<form method="get">
<p>
<input type="hidden" name="ID" value="<? echo $ID; ?>">
<p><label>Name: </label>&nbsp;

<? echo "<input type=\"text\" name=\"Name\" value=\"$Name\">"; ?>

</p>
<p><label>Telephone: </label>&nbsp;
<? echo "<input type=\"text\" name=\"Telephone\" value=\"$Telephone\">"; ?>
</p>
<label>Birthday: </label>&nbsp;
<? echo "<input type=\"text\" name=\"Birthday\" value=\"$Birthday\">"; ?>

<br>
<br>
<input name="abc" type="Submit" value="Update">
</p>
</form></td></tr></table>

</body>
</html>


If someone could help me, it would be great!

Thx guys

[edited by: eelixduppy at 9:13 pm (utc) on Jan 30, 2012]
[edit reason] no personal URLs, please [/edit]

rocknbil

4:43 pm on Jan 30, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here
$sql="UPDATE tableName
SET Name='$Name', Telephone='$Telephone', Birthday='$Birthday'
WHERE ID = $ID";

add

echo $sql;
exit;

I'll guess that $ID is null/empty. This is really a good thing, if it were quoted it wouldn't error, it just wouldn't work, so using no quotes on a numeric field query is a good approach.

If $ID is not empty, see if the echoed command will run when pasted into phpMyAdmin.

fulanitok

5:29 pm on Jan 30, 2012 (gmt 0)

10+ Year Member



Hi rocknbil

I will try this later and let you know!

Thx for your help!

fulanitok

6:53 pm on Jan 30, 2012 (gmt 0)

10+ Year Member



Uffff!

I really don't know what's going on! I'm looking now for days for a solution for this issue but can't find that.

* Notice: Undefined variable: ID in C:\Users\------\Documents\xampp\htdocs\database\update.php on line 42
* Notice: Undefined variable: Name in C:\Users\------\Documents\xampp\htdocs\database\update.php on line 53
* Notice: Undefined variable: Telephone in C:\Users\------\Documents\xampp\htdocs\database\update.php on line 57
* Notice: Undefined variable: Birthday in C:\Users\------\Documents\xampp\htdocs\database\update.php on line 60

My only goal, trying to make this update.php to work, is to learn how to write the data back to MySQL so I can modify the first code (search.php) and make a editable form.

Really frustrating...

fulanitok

7:02 pm on Jan 30, 2012 (gmt 0)

10+ Year Member



When press "UPDATE" this shows up:

* Notice: Undefined index: licencenr in C:\Users\-------\Documents\xampp\htdocs\database\update.php on line 14
* Notice: Undefined index: first in C:\Users\-------\Documents\xampp\htdocs\database\update.php on line 15
* Notice: Undefined index: mobile in C:\Users\-------\Documents\xampp\htdocs\database\update.php on line 16
* Notice: Undefined index: birth in C:\Users\-------\Documents\xampp\htdocs\database\update.php on line 17
* UPDATE members SET Name='', Telephone='', Birthday='' WHERE ID =

A real MESS, I don't think to be able to do it! My php background is way too small.

Perhaps I should be realistic and just let it go and just use the first code (search.php) like it is. To modify user's data it tricky, I will use MS Access offline then export to .csv and upload to MySQL! Again ufffff...

I really didn't know it was so hard to do this, no one but "rocknbil" was able to help me out this... But like I said my php background is almost inexistent.

OK, thx for your help.

fulanitok

8:32 am on Jan 31, 2012 (gmt 0)

10+ Year Member



Hi there!

Ok guys I figured out by my self :cool: but I will help those like me are looking for an answer to the question: How to manage a MySQL database form a PHP Form?

Here do you have the answer and example: http://www.wupload.com/file/2656203917/mysqlDatabaseManagement.rar [wupload.com]

Have fun...

Fulanitok

g1smd

8:42 am on Jan 31, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



One design pattern you should try to follow is to have all the PHP database interactions coded before you send the HTML DOCTYPE out.

This then allows you to send the correct HTTP 404 HEADER when there is no record in the database for the current URL request.

It is too late to send HTTP headers once you have started to send the HTML page to the browser.

rocknbil

5:04 pm on Jan 31, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



When press "UPDATE" this shows up:


It's not that difficult once you know what's happening. One of the problems with beginner [insert language of choice here] coders is going around the Internet copying and pasting code without understanding what it's doing.

It's telling you those variables haven't been set, which leads you to WHY they haven't been set. Look here:

if (isset($_GET["abc"]))
{
$ID=$_POST['licencenr'];
$Name = $_POST['first'];
$Telephone = $_POST['mobile'];
$Birthday = $_POST['birth'];
}

What does your error tell us? One possibility is that $_GET['abc'] is not set so it nevers does what you ask inside the "if". Also look at these two: $_GET and _POST. You're checking if abc is in GET, then check for POST values inside the "if". So even if $_GET['abc'] is set, this tells us the form is using the get method, but you're checking for values in POST, which won't exist. IF your form uses post, $_GET['abc'] will never be set.* See the problem?

In either case, your program goes on and tries to use $ID, $Name, etc, and they aren't defined yet.

(* The exception is if you do this: <form action="editscript.php?abc=1" method="post"> which is just . . . weird and unnecessary . . . put abc in a hidden field in the form and look for it in post.)

<form action-"editscript.php" method="get">

If method is omitted, it defaults to get.

<form action="editscript.php">

Let's get rid of all the ugly query strings in the URL caused by GET and use POST instead:
<form action-"editscript.php" method="post">
if (isset($_POST["abc"]))
{
$ID=$_POST['licencenr'];
$Name = $_POST['first'];
$Telephone = $_POST['mobile'];
$Birthday = $_POST['birth'];
}

Returning to the original problem, the errors, a better error trapping method should be used that checks if values are set before you try to use them. This is true of **any** programming you do: check that a value is set before you use it (and that it's the right type, and clean, but that's a topic for another thread.) Note how this at least sets the values for your variables before using them. It may still not "work" if you missed something, but it won't error. :-)


if (isset($_POST["abc"])) {
$ID=(isset($_POST['licencenr']))?$_POST['licencenr']:null;
$Name=(isset($_POST['Name']))?$_POST['Name']:null;
$Telephone=(isset($_POST['Telephone']))?$_POST['Telephone']:null;
$Birthday=(isset($_POST['Birthday']))?$_POST['Birthday']:null;
}


Those one-liners,
$ID=(isset($_POST['licencenr']))?$_POST['licencenr']:null;

are called ternary operators or short-circuit evaluation. The previous line is exactly the same as this longer version:

if (isset($_POST['licencenr'])) {
$ID=$_POST['licencenr'];
}
else{
$ID=null;
}