I am working on a project which allows me to create a customer database. I have made an Create.php and Delete.php but am having issues with the basic structure for an Edit page.
My initial idea is to create a populated drop down box (Which I can do) which on click will take the user to domain.com/Customer.php?Customer_name="JohnD"
I am having a few issues with regards to this as it is doing 2 things.
It is printing out ALL of the data in my table into the echo.
It isn't taking the values from the URL, However I know that I have missed something but am unsure of what I need to search for.
Here is my snippet so far:
<h2>
<?Php
$sql="SELECT id,customer_name FROM Customers";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<?Php echo $data['customer_name']; } ?>
</h2>
As of yet I am getting this in the header:
John Doe Jimmy Timmy Test
These are all the values inside my rows for the table Customers.
Sorry if the question seems all over the place. I will correct if it is not easy to understand.
Thanks in advance
use this url
domain.com/Customer.php?CID=1
and the code should look like
<?php
$customer_id = (int) $_GET['CID'];
$query = "SELECT id, customer_name FROM Customers
WHERE id = {$customer_id}";
$result = mysql_query($query) or die('<p>' . $query . '</p><div>' .
mysql_error() . '</div>');
$customer = mysql_fetch_assoc($result);
?>
<h2><?php echo $customer['customer_name'] ?></h2>
You need to use $_GET to get the parameters from the URL.
<?php
//customer.php?Customer_name=JohnD (no quotes)
echo $_GET[Customer_name];
?>
You would then use mysqli_ or PDO to bind $_GET[Customer_name] and execute the query. If you don't bind parameters in your SQL query, you will be vulnerable to SQL injection.
You need to restrict the SQL select to the specific customer with a where clause. And you may be getting that customer id from the request. I would suggest that you use customer id rather than name in the drop down box. That way the URL will be:
domain.com/Customer.php?id=1
On the Customer.php page you can get the value using $id = $_GET['id'];
Now as for your SQL you should use some safer method for querying the database say:
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'myun';
$password = 'mypw';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
$stmt = $dbh->prepare("select id, Customer_name from customers where id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
while($c = $stmt->fetch()){
echo $c['customer_name'];
}
This way only data for the selected customer will be displayed.
Related
I am a beginner in PHP and i am currently working on making an online youth mentorship portal for my project. What my system will basically do is ask mentors and mentees to sign up. Mentors will pick the categories in which they wish to mentor in. Once mentees login, they will be redirected to a page with the list of categories available for mentorship. What i'm having a problem in is extracting data from the database based on what category the mentee clicks on. I'm sorry for being so daft but i'm a rookie and i've traversed the net but to no avail.
Here is my categoryindex.php page:
<h2>Choose the category you want to be mentored in:</h2><br><br>
<li>Music</li><br>
<li>ICT</li><br>
<li>Politics</li><br>
<li>Entrepreneurship</li><br>
<li>Sports</li><br>
<li>Religious</li><br>
<li>Agriculture</li><br>
<li>Finance & Banking</li><br>
<li>Leadership</li><br>
<li>Science</li><br>
<li>Fashion/Beauty</li><br>
<li>Medical</li>
Here is my script.php page(can't understand how to reference the "where category=" part:
<?php
require('db.php');
session_start();
$_SESSION['selected_category']-> $_GET['category'];
mysqli_select_db($con,'ymp');
$query = "SELECT * FROM mentor WHERE category =?";
$result = mysqli_query($con,$query) or die ("Failed to query database" . mysqli_error($con));
$rows = mysqli_num_rows($result);
?>
Kindly help me out. Thank you
You need to replace the question-mark with a value, in this case the $_GET['category'] variable.
Best practice is to use prepared statements:
<?php
require('db.php');
session_start();
$mysqli = new mysqli('host', 'username', 'password', 'database');
$stmt = $mysqli->prepare("SELECT * FROM mentor WHERE category = ?");
$stmt->bind_param('s', $_GET['category']);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->num_rows;
?>
If you don't declare this value, the query won't run.
Hope this helps, if not just ask and I could take another look at your code!
I'm busy with a school project where I need to register users. I created the database and added the tables and can add users. What I just can't get right is to display the next available user id in the table.
I'm using php to retrieve the highest value but when I use echo the variable won't show. There is no error, there is no output at all, just the rest of the page.
Here is the code:
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM users" or
die(mysql_error());
$highest_id = mysqli_query($db, $query);
echo $highest_id;
?>
The code successfully connects to the database, the column is called userid, it contains int values and there are other columns as well.
All other code in the script runs perfectly, it's just this part that I can't get to work.
I have spent the last two days reading and searching for answers and I am at my wits end. Any help would be appreciated.
Thank you.
could be your table is User and not Userid
$query = "SELECT MAX(userid) AS userid FROM users"
Anyway for fetching you should use eg:
$result = mysqli_query($db, $query);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0];
The mysqli_query returns a general object that contains the results array. You have to use the mysqli_fetch_row.
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM userid" or die(mysql_error());
$highest_id_query = mysqli_query($db, $query);
var_dump($highest_id_query); // so you could check the object attributes
//loop results from query
while($row=mysqli_fetch_row($highest_id_query)){
$highest_id = $row['userid'];
echo $highest_id;
}
?>
You could also use the sql statement: SELECT COUNT(*) FROM userid
Be sure to name your tables correctly! SELECT COUNT(*) FROM users
I'm developing an app for android that uses a DB on a server.
I wrote some script php to create new rows in some tables and get all elements from a table (using JSON to exchange data between android and mysql).
Now I have a problem:
i need to select an id from a table and then use this to insert a row in anothere table that has this foreign key.
Well, when I try to select my id, i don't know why, but look like it doesn't work.
Here a simple example how I select this id:
//connect to DB...
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
When i use this to select an id, and put it in another query (always on the same connectio) nothing is stored.
if I force the value manually, and so in the same second query I put a number of a preesisting id, the insert works, so the problem is in this piece of code.
Hope someone could help me.
Thank you!
The code that you have put on the question, contains syntax errors.
- Remove * from the start of query
- put the query inside " "
- remove single quote ('table') from table name
Here is the modified code:
//connect to DB...
$result = mysql_query ("SELECT id FROM table WHERE name = $name" );
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Also you should escape the parameter $name in query. And you should use mysqli or PDO instead of mysql extension.
try this:
$result = mysql_query (*SELECT id FROM 'table' WHERE name = $name );
$row = mysql_fetch_assoc($result);
while($row > 0){
$id = $row['id'];
}
I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php
another day another question...
I need to write PHP script to update mySQL database.
For example: updating profile page when user want to change their first name, last name or etc.
Here is my php script so far, it doesn't work. Please help!
<?php
# $db = new MySQLi('localhost','root','','myDB');
if(mysqli_connect_errno()) {
echo 'Connection to database failed:'.mysqli_connect_error();
exit();
}
if (isset($_GET['id'])) {
$id = $db->real_escape_string($_GET['id']);
$First_Name2 = $_POST['First_Name2'];
$query = "UPDATE people SET $First_Name2 = First_Name WHERE `Id` = '$id'";
$result = $db->query($query);
if(! $result)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully\n";
$db->close();
}
?>
THank you.
Your sql is wrong. Apart from the gaping wide open SQL injection attack vulnerability, you're generating bad sql.
e.g. consider submitting "Fred" as the first name:
$First_Name2 = "Fred";
$query = "UPDATE people SET Fred = First_name WHERE ....";
now you're telling the db to update a field name "Fred" to the value in the "First_Name" field. Your values must be quoted, and reversed:
$query = "UPDATE people SET First_name = '$First_Name2' ...";
You are also mixing the mysqli and mysql DB libraries like a drunk staggering down the street. PHP's db libraries and function/method calls are NOT interchangeable like that.
In short, this code is pure cargo-cult programming.