I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
Related
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'];
}
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.
I'm trying to pull some information from a database, and the connection is working, but for some reason it isn't recognizing my query, even though I confirmed the query in the database with SQL and had it "generate PHP code". The echo statement is coming up blank. It's a mySQL database. Thanks for your help.
$query = "SELECT `contact` FROM `contactinfo` WHERE member=\'Henry\'";
$contact = mysqli_query($db,$query);
echo $contact;
$contact contains MySQL result object you need to fetch data from this to use this in your application.
$query = "SELECT `contact` FROM `contactinfo` WHERE member = 'Henry'";
$contact = mysqli_query($db, $query);
while ($row = mysqli_fetch_row($contact)) {
echo $row[0]; // 0 to n indicates the Column(s) Selected in SELECT Query
}
I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.