Why does this SQL query not work? - php

I have been bugging by head over this, but couldn't get this to work. What's wrong with this?
$query="Select studentid,firstname,lastname,pts from students where collegeid=4";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
$pts=$row['pts'];
$name=$row['firstname']." ".$row['lastname'];
$rank= mysql_num_rows(queryMysql("Select distinct pts from students where pts>=$pts"));
echo<<<_END
<a href="student_profile.php?studentid=$row[studentid]" style="text-decoration: none;">
<div class="apps_each your_rank">
<span style="margin-right:5px;">$rank</span>
<div class="dp_small_c"><img class="dp_small" src="upload/$row[studentid].jpg"/></div>
<span class="apps_names">$name</span>
<div style="float:right">
<img src='pts.png' /><span>$row[pts]</span>
<img src='level.png' /><span>Level 1</span>
</div>
</div>
</a>
_END;
The 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 1.
Surprisingly, below one(removing the WHERE clause) works. Why?
$row=mysql_fetch_array(mysql_query("Select studentid,pts,firstname,lastname from students"));
Table structure:
Everything's fine with table and its columns, because this query works everywhere else, only not here!

You mentionned in the comments that you wanted to use PDO. Here's what you can try:
$username = "enterUsername";
$password = "enterPass";
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$query = $conn->prepare("Select studentid,pts,firstname,lastname from students where collegeid=:id");
$query->execute(array(
':id' => 4
));
// get errors if there are
$errors = $query->errorInfo();
echo "<pre>";
print_r($errors);
echo "</pre>";
$results = $query->fetch(PDO::FETCH_ASSOC); // can also be fetchAll if you have more than 1 row.
// to test and check results
echo "<pre>";
print_r($results);
echo "</pre>";

if $query in the question returns an empty row, then the variable beneath it remained unassigned - i.e., $pts and $name have no entities.
However, the query below them uses the variable $pts, which presumably has to store some value - which, when not, throws the above posted MYSQL error. The use of function queryMysql() for this query further clears the issue, as it was defined as below:
function queryMysql($query)
{
$result=mysql_query($query) or die(mysql_error());
return $result;
}
Hence, the MySql error.

I would use this library for all MySQL querying - http://www.meekro.com.
Your select query becomes like this:
// Load Library
require 'meekrodb.2.2.class.php';
// Setup DB Connection
DB::$user = 'my_database_user';
DB::$password = 'my_database_password';
DB::$dbName = 'my_database_name';
DB::$host = '123.111.10.23';
// Where clause
$collegeid = 4;
// Exec Query
$row = DB::queryFirstRow("Select studentid,pts,firstname,lastname from students where collegeid = %d", $collegeid);
src: http://www.meekro.com/docs.php#anchor_queryfirstrow

Related

Insert link into database as a href tag

I am having an issue by inserting a link in the database. I am generating links through several conditions but in the end, I get an error when I try to insert a link in the database.
Also, I am pulling a description from the database then adding these links to the existing description and then updating the value.
$parent_path = 'https://sitename.com/game/'.$parentSlug;
$parentLink = ''.$parentName.'';
$child_path = 'https://sitename.com/game/'.$slug;
$childLink = ''.$name.'';
I am facing several errors during a script run
Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 's also a CBD education section to help you make the best decision when making...'
$sql = "SELECT * FROM `wpdev_postmeta` where post_id = $post_id and meta_key = 'test'";
$q = $conn->query($sql);
while($r = $q -> fetch()){
$description = $r['meta_value'];
}
$description may contain "a href tag ", when I echo it, it becomes a clickable link and not able to update field in db.
$desc = $description.'<br/>'.$parentLink.$childLink;
$stmt = "UPDATE wpdev_postmeta SET meta_value = '$desc' WHERE meta_key = 'test' and post_id = $post_id ";
if ($conn->query($stmt)) {
echo "Record updated successfully". '<br/>';
} else {
echo "Error updating record: " . '<br/>';
}
For future reference, do I need to get data first from database then send it again with new update in case I don't want to lose what is inserted before? I was googling but couldnt find appropriate answer.
If you need save HTML to database you can use two different way
Using prepared statements. Look to PDO or MySLi
Encoding all tags and other special symbols for example via htmlentities or htmlspecialchars.
Example for htmlentities:
<?php
$link = 'Check that';
echo(htmlentities($link, ENT_QUOTES|ENT_HTML5));
// output:
/*
<a href&equals;"https&colon;&sol;&sol;stackoverflow&period;com&sol;">Check that<&sol;a>
*/
?>
For decode to HTML use html_entity_decode
<?php
$encoded = '<a href&equals;"https&colon;&sol;&sol;stackoverflow&period;com&sol;">Check that<&sol;a>';
echo(html_entity_decode($encoded, ENT_QUOTES|ENT_HTML5));
// output
/*
Check that
*/
?>
Example for htmlspecialchars:
<?php
$link = 'Check that';
echo(htmlspecialchars($link, ENT_QUOTES|ENT_HTML5));
// output
/*
<a href="https://stackoverflow.com/">Check that</a>
*/
?>
For decode from htmlspecialchars:
<?php
$encoded = '<a href="https://stackoverflow.com/">Check that</a>';
echo(htmlspecialchars_decode($encoded, ENT_QUOTES|ENT_HTML5));
// output
/*
Check that
*/
?>

Delete record and count rows to check for result

So Im trying to delete a record from a table using php and sql and check whether it has been deleted using a rowcount() function in an if statement.
Im having problems on both fronts...
<?php
echo $_GET['id'];
if (isset($_GET['id'])) {
$trainingID = $_GET['id'];
}
else {
die('There was a problem with the ID given.');
}
// include the connection file
require_once('./includes/connection.inc.php');
$conn = dbConnect();
// prepare SQL statement
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
$stmt = $conn->prepare($sql);
try {
$stmt->execute();
echo "deleted";
echo $stmt->rowcount();
//check number of rows affected by previous insert
if ($stmt->rowCount() == 1) {
$success = "$trainingID has been removed from the database.";
}
}
catch(PDOException $e){
echo $e;
echo 'Sorry, there was a problem with the database.';
}
?>
I currently get 3 things outputted from my echo's throughout my code, firstly i get T0001, which is the primary key of the record i want to delete from another page. Secondly i get "deleted" which is from an echo within my 'try' statement but the record doesn't actually delete from the database. This is backed up from the rowcount() function which outputs 0.
I can't seem to get this working and im sure it should be simple and is something i am just overlooking!
Will the try method default to the catch if the "if" statement in it fails? As im also unsure what should be output from a rowcount() when a row has been deleted?
Any help you could offer would be really helpful! Thanks!
echo'ing this line
$sql = 'DELETE FROM `trainingCourses` WHERE `trainingID` = "$trainingID"';
will treat $trainingID as string and not variable.
$sql = "DELETE FROM `trainingCourses` WHERE `trainingID` = '$trainingID'";
will do the work BUT its not safe (sql injections). You should use PDO to bind varaibles like this
$sth = $dbh->prepare("DELETE FROM `trainingCourses` WHERE `trainingID` = :id");
$sth->bindParam(":id",$trainingID);
$sth->execute();

PHP-PDO try/catch inserting dynamic html link

it seems i have run into a slight problem in my first shot at using PDO and prepared statements. Basically I am working on a profile page which includes an Inbox. I am using try/catch to produce the inbox:
<?php
$sqlin = $db->prepare("SELECT * FROM message WHERE recipientID = (SELECT id FROM members WHERE username = '$pageowner')");
try {
while($row = $sqlin->fetch(PDO::FETCH_ASSOC)){
?>
<br><?php echo $row['title'] ?>
<?php
}
}
catch(PDOException $e) {
die ($e->getMessage());
}
?>
So this is supposed to relate the user id to the recipient id, and then create links to the messages. When I run in browser no links are listed
Is this an issue within my try/catch syntax? maybe stopping the php and inserting the html?--I tried echoing out but ran into problems creating that code.
You have to start to try/catch the exception before the prepare() and after it. And please use prepared statement, with prepare() method. Otherwise, you are defeating the purpuse of PDO by directly placing your variables inside the query. Which does not make your script safer from mysql injection.
$pageOwner = 'some external data';
try {
$sqlin = $db->prepare("
SELECT * FROM message
WHERE recipientID = (
SELECT id
FROM members
WHERE username = ?
)
");
$sqlin->execute(array($pageOwner));
}catch(PDOException $e){
die ($e->getMessage());
}
while($row = $sqlin->fetch(PDO::FETCH_ASSOC)){
?>
<br><?= $row['title'] ?>
<?php } ?>
first, you shouldn't use try..catch here at all.
Instead, you have to call execute() and use prepared statements.
Also you have to separate your SQL from HTML.
Here is the proper code.
<?php
$sql = "SELECT m.* FROM message m, members mm WHERE recipientID = mm.id and username = ?";
$stm = $db->prepare($sql);
$stm->execute([$pageowner]);
$data = $stm->fetchAll();
?>
<?php foreach ($data as $row): ?>
<br><?=$row['title'] ?>
<?php endforeach ?>

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Pull data from Mysql Into Dropdown

**UPDATED
<?php
// Get select box of courses to comment on
$pID3 = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
$username = "###";
$password = "###";
$pdo3 = new PDO('mysql:host=localhost;dbname=###', $username, $password);
$pdo3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth3 = $pdo3->prepare('
SELECT C.prefix, C.code
FROM Department D, Course C
WHERE D.dID = C.dID
**AND pID = ?**
');
$sth3->execute(array(
$pID3
));
?>
<html>
<?php
echo "<form action='inc/q/prof.php' method='post'>
<select id='courseInfoDD' name='courseID' tabindex='1'>";
?>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix'].", ".$row3['code']."</option>";
}
?>
<?php
echo "</select>";
?>
</html>
Okay, so right now its pulled all courses regardless of the pID or (Professor ID). I added a statement in the select saying where pID = ? , since the pID is in the url of the page. But now it throws and error about pID???
Query:
SELECT C.prefix, C.code
FROM Department D, Course C, Professor P
WHERE pID = ?
AND D.dID = C.dID
AND D.dID = p.dID;
Phpmyadmin 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 '? AND D.dID = C.dID AND D.dID = p.dID LIMIT 0, 30' at line 3
Db Img: http://postimage.org/image/24gdqab8k/
and
http://postimage.org/image/24gfdtnqc/
Okay. You need to follow some basic debugging steps. Here's exactly how to fix the problem:
First, my #1 guess about what's going on.... reading over your code, an empty data set will produce an empty select box. So start with the most simple: have you tried your SQL query directly on the database (i.e. with something like phpMyAdmin or the SQL command-line tool)? Be sure it works and (just as importantly) returns data.
If that works, then move the fetch call up into the PHP at the top, and just fetch the data and echo it to the screen (in other words, remove all the HTML). This will at least show you if it's fetching data from the database and your PHP PDO calls are correct.
Finally, if that doesn't seem like anything is wrong, find out if the PDO library is throwing a SQL error. Maybe it can't connect to the database; maybe your query returns empty rows. Very simple:
print_r($sth3->errorInfo());
Have you done a "view source" on the output? Is it writing out any of the option tags? bensiu's answer is correct, in that you need double quotes, not single quotes, around your "print" statement.
I promise that if you follow these steps, your code will work ;-)
print "<option>{$row3}</option>";
or
echo "<option>$row3</option>";
double quotes and you are missing <?php and `?>' tags
<select id='courseInfoDD' name='courseID' tabindex='1'>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>$row3</option>";
}
?>
</select>
If that
<select id='courseInfoDD' name='courseID' tabindex='1'>
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>$row3</option>";
}
</select>
really is all your HTML, then your problem is, that that’d HTML and not PHP. You wanted to make it PHP, right?
<select id='courseInfoDD' name='courseID' tabindex='1'>
<?php
while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo '<option>$row3</option>';
}
?>
</select>

Categories