Selecting table data with PDO statements [duplicate] - php

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
I have a php script that selects data via mysql_, however recently I have been reading that PDO is the way to go and that mysql_ is becoming depreciated. Now I am converting that script to PDO.
My question is though, I am not using $_POST to select. I just want to select the entire table with all of its data so I enter this query :
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchall(); // or you can just $result = $query as hakre proposed!
so then like I did with my old depreciated mysql_ version of the script I used the echo to echo a table with the data in it.
echo
"<table border='2'>
<tr>
<th>ID</th>
<th>A Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Why</th>
<th>Comments</th>
<th>Signintime</th>
</tr>"
;
foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" .$row['anum'] . " </td>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['why'] . "</td>";
echo "<td>" . $row['comments'] . "</td>";
echo "<td>" . $row['signintime'] . "</td>";
echo "<td> <input type=\"button\" value=\"Start Session\"onClick=\accept.php?id=" . $row['id'] . "&start=true></td>";
}
echo "</tr>";
echo "</table>";
now using this, I can not get a single output to my table.
My question is am I missing something from my select statements? Or am I not fetching any rows? Also I the connection settings set in another script called connect.php that is required by init.php (at the top of all of my pages)
Edit : 1
Edited the code so it now works, also adding a picture to show others how it should look! Hopefully some one can put this to some sort of use!

You are doing too much actually:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
The problematic line is:
$result = $dbh->query($query);
Check with http://php.net/pdo.query, the parameter is a string, actually the SQL string you already use above, not the result value of a PDO::prepare() call.
For your simple query you can just do:
$result = $dbh->query("SELECT * FROM students");
Or if you like to prepare:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query;
The later is some boilerplate if you want to insert variables into the query, that's why you prepare it.
The next problem is with the foreach line:
foreach($result as $row);
You are terminating the loop immediately because of the semicolon ; at the end. Remove that semicolon so that the following angle-bracketed code-block becomes the body of the foreach-loop.

Your code is wrong:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
After executing a prepared statement, you can just call fetchAll() on it:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchAll();
The rest of your code will work fine once you remove the semicolon after the foreach.

Related

Oracle Database won't output in my PHP table

I'm trying to output the data from a specific table within my Oracle SQL Developer database using a PHP form. I had some experience with this concept in the past using MySQL but I'm struggling to understand the differences between integrating it using Oracle specific syntax now.
My code is ideally laid out but when I run the code I get an error regarding the OCI_FETCH_ARRAY parameters, which I'm unsure on how to solve.
My Code
<?php
include("../connection.php");
error_reporting(E_ALL);
$sql = 'SELECT * FROM ALGORITHM';
$stid = oci_parse($conn, $sql);
echo "<table border='1'>";
echo "<tr> <th>ID</th> <th>Name</th> <th>Description<th> </tr>";
while($row= oci_fetch_array($stid, $sql))
{
echo "<tr>";
echo "<td>" . $row ['Algorithm_ID'] . "</td>";
echo "<td>" . $row ['Algorithm_Name'] . "</td>";
echo "<td>" . $row ['Algorithm_Role'] . "</td>";
echo "</tr>";
}
echo "</table>";
oci_free_statement($stid);
oci_close($conn);
?>
The Error I keep getting
Warning: oci_fetch_array() expects parameter 2 to be integer, string
given in
/studenthome.hallam.shu.ac.uk/STUDENTHOME8/1/b5040831/public_html/ADM/bin/php/entities/database.php
on line 12
I get that it's asking for an integer, but why? In the MySQL concept you simply outline the connection string it was never an issue.
Can anyone help ?
Calling oci_fetch_array() ( from http://php.net/manual/en/function.oci-fetch-array.php) should be called like
while($row= oci_fetch_array($stid))
The second parameter is the mode - i.e. OCI_ASSOC.
Update: when using oci_parse(), this doesn't actually execute the parsed statement, you need to do...
oci_execute($stid);
So your code would be something like...
$sql = 'SELECT * FROM ALGORITHM';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
echo "<table border='1'>";
echo "<tr> <th>ID</th> <th>Name</th> <th>Description<th> </tr>";
while($row= oci_fetch_array($stid, OCI_ASSOC))
(Look at http://php.net/manual/en/function.oci-parse.php for code examples)

Using PHP variable in mysql_query string

OK guys. I have a somewhat complicated issue with passing PHP variables into the mysql_query string.
The $_GET['date']; when passed will contain something like: 2015_01_07_1
I need to have the GET data passed into the table names using the $week variables.
<?php
$week= $_GET['date'];
$con=mysqli_connect("localhost","root","mypassword","beerhandpoker");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query
($con,
"SELECT games_brixx_gastonia_'$week'.rank, players_brixx_gastonia.name, games_brixx_gastonia_'$week'.points
FROM games_brixx_gastonia_'$week', players_brixx_gastonia
WHERE games_brixx_gastonia_'$week'.email = players.email
ORDER BY games_brixx_gastonia_'$week'.rank
LIMIT 20"
);
echo "<table>
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['rank'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['points'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Change the string literal to:
"SELECT games_brixx_gastonia_$week.rank,
players_brixx_gastonia.name,games_brixx_gastonia_$week.points
FROM games_brixx_gastonia_$week, players_brixx_gastonia
WHERE games_brixx_gastonia_$week.email = players_brixx_gastonia.email
ORDER BY games_brixx_gastonia_$week.rank
LIMIT 20"
You have to remove the ' characters;
It's going to the db as games_brixx_gastonia_'2015_01_07_1'.rank
Why do you put single quotes? It should work:
SELECT games_brixx_gastonia_{$week}.rank, players_brixx_gastonia.name, games_brixx_gastonia_{$week}.points
FROM games_brixx_gastonia_{$week}, players_brixx_gastonia
WHERE games_brixx_gastonia_{$week}.email = players.email
ORDER BY games_brixx_gastonia_{$week}.rank
LIMIT 20
Anyway, I'd rather advice you to use statement instead. Check it out:
http://php.net/manual/pt_BR/mysqli.prepare.php
Just remove the ' characters. Otherwise the query would try to get data from the table games_brixx_gastonia_'2015_01_07_1' and not games_brixx_gastonia_2015_01_07_1.

mysqli_fetch_array(), prepared statement, and LIKE statement

I'm trying to use mysqli prepared statements with a LIKE statement query and wildcard operators. After debugging be sprinkling echo statements throughout the code, I can see that my while statement is not executing. Can you see what I'm doing wrong here?
This is my first time asking on this forum, so I apologize if this isn't a good question; I've spent 6 hours trying to get the prepared statement section of my code to work and I can't find any threads addressing my question that don't go completely over my head (e.g. How can I put the results of a MySQLi prepared statement into an associative array?). The two closest I found were:
Using wildcards in prepared statement - MySQLi
and Combine PHP prepared statments with LIKE.
Here's the relevant excerpt of my code:
//set up and execute queries
$titleQuery = "SELECT keyframeurl, videoid, title, creationyear, sound, color,
duration, genre FROM openvideo WHERE title LIKE CONCAT ('%', ?, '%')
ORDER BY $order";
if($stmt = mysqli_prepare($db, $titleQuery)){
//bind parameters
mysqli_stmt_bind_param($stmt, 's', $trimmedTitleSearch);
//execute query
mysqli_stmt_execute($stmt);
//bind results
mysqli_stmt_bind_result($stmt, $keyframeurl, $videoid, $title, $year, $sound,
$color, $duration, $genre);
//store result so num rows can be counted
$result = mysqli_stmt_store_result($stmt);
//fetch results
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>".$row['videoid']."</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['year'] . "</td>";
echo "<td>" . $row['sound'] . "</td>";
echo "<td>" . $row['color'] . "</td>";
echo "<td>" . $row['duration'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "</tr>";
}
}
else {
// Error
printf("Prepared Statement Error: %s\n", $db->error);
}
Thanks for any advice!
You are mixing 2 styles of fetching results. Either use ugly bind_result way (and get your data using fetch() then), or try to use get_result() - so, you'll be able to use fetch_array() (not guaranteed though).
Anyway, just get rid of all that mess and use PDO.
$titleQuery = "SELECT keyframeurl, videoid, title, creationyear, sound, color,
duration, genre FROM openvideo WHERE title LIKE CONCAT ('%', ?, '%')
ORDER BY $order";
$stmt = $pdo->prepare($titleQuery);
$stmt->execute(array($trimmedTitleSearch));
$data = $stmt->fetchAll();
foreach ($data as $row ) {
// the rest is the same as yours
I hope you properly sanitized your $order variable. The best way would be apparently to add it via placeholder, so, you will need a library that allows it, SafeMysql for example:
$sql = "SELECT * FROM openvideo WHERE title LIKE CONCAT ?s ORDER BY ?n";
$data = $db->getAll($sql,"%$trimmedTitleSearch%", $order);
foreach ($data as $row ) {
// the rest is the same as yours
Note the amount of code and compare with that load of raw API calls you are using at the moment
#Your Common Sense - You see there is no need for allenbell_nc to "... just get rid of all that mess and use PDO" like you inferred. Just because you've got an erroneous impression of the mysqli extension with prepared statements does not mean that others should do away with it at the slightest hint of trouble as opposed to carrying out indepth but painful research. After all, this is what stackoverflow is about, isn't it? well researched answers..
#allenbell_nc - To answer your question, I do not think your problem has to do with your use of Wild cards and stuff. The problem lies in your line of code where you attempt to make use of
mysqli_fetch_array(). This will very likely throw an error complaining about parameter 1 ($result), because mysqli_stmt_store_result() is used in cases where you want to later find the number of rows returned from a query, so it therefore returns boolean(true or false) and NOT a result set.
INSTEAD, use mysqli_stmt_bind_result() after the execute call then call mysqli_stmt_fetch()in the while condition, before finally using array_push() in the while condition body which will help you to store and subsequently echo out the contents of your ASSOCIATIVE array.
A QUICK EXAMPLE(Idea provided by Mr. Carson McDonald # [http://www.ioncannon.net/programming/889/php-mysqli-and-multiple-prepared-statements/][1]):
...
$comments = array();
$comment_stmt->bind_param('i', $post_id);
if ($comment_stmt->execute())
{
$comment_stmt->bind_result($user_id);
while ($comment_stmt->fetch())
{
array_push($comments, array('user_id' => $user_id));
//Now you can go ahead and make use of $comments however you want, whether as stored in an $_SESSION array variable or just to echo it out! As Demonstrated Below:
$_SESSION = $comments;
echo $_SESSION['user_id'];
}
}
...
Hope that helps, goodluck to you - a first time asker, as this is also my first time answer - on your project.
echo "<td>" . $row['color'] . "</td>";
echo "<td>" . $row['duration'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "</tr>"; while ($row = mysqli_fetch_array($stmt, MYSQL_ASSOC))
Or while ($row = mysqli_stmt_fetch($stmt))
Edit:
mysqli_stmt_bind_result($stmt, $keyframeurl, $videoid, $title, $year, $sound,
$color, $duration, $genre);
//store result so num rows can be counted
$result = mysqli_stmt_store_result($stmt);
//fetch results
while (mysqli_stmt_fetch($stmt)) {
echo "<tr>";
echo "<td>".$videoid."</td>";
echo "<td>" . $title . "</td>";
echo "<td>" . $year . "</td>";
echo "<td>" . $sound . "</td>";
echo "<td>" . $color . "</td>";
echo "<td>" . $duration . "</td>";
echo "<td>" . $genre. "</td>";
echo "</tr>";
}

Add database fields according to id php [duplicate]

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 9 years ago.
I've been trying to output my database fields according to their empid, but I somehow can't. it gives me this error..
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:_webhost\Apache24\htdocs\eis\usercp.inc.php on line 16
<?php
$firstname = getuserfield('txtFname');
$lastname = getuserfield('txtLname');
echo 'Hello '.$firstname.' '.$lastname.'.';
$empid = getuserfield('empid');
$query = "SELECT type_of_leave,specific_reason,date_from,date_to,num_of_days FROM `hrf_leave` WHERE `empid` = '$empid' AND `formStatus` = 0";
$query_run = mysql_query($query);
echo "<table border=1>
<tr>
<th>Type of Leave</th>
<th>Specific Reason</th>
<th>Date From</th>
<th>Date To</th>
<th>Number of Days</th>
</tr>";
while($record = mysql_fetch_array($query_run)){ // line 16
echo "<tr>";
echo "<td>" . $record['type_of_leave'] . "</td>";
echo "<td>" . $record['specific_reason'] . "</td>";
echo "<td>" . $record['date_from'] . "</td>";
echo "<td>" . $record['date_to'] . "</td>";
echo "<td>" . $record['num_of_days'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
A boolean false is passed from mysql_query() since your sql statement $query is invalid. Therefor mysql_fetch_array() returns the above error.
Try this as $query, it will solve if it is a syntax error I hope.
$query= SELECT * FROM hrf_leave WHERE empid = '$empid' AND formStatus = 0";
See there might be 2 things :-
First the empid you used in the query might be integer and you are passing the value with in quotes.
Second the query is not returning any result. echo out the query and run it in the phpmyadmin or any mysql query browser.
Suggestion : Before using mysql_fetch_array use mysql_num_rows to check that if any rows are returned from the query.
Note : mysql_* functions are being depreciated. So avoid them
Before you do anything please try to not use mysql_ function its no more supported
You can use pdo. Bellow is how to connect to the datadabase using pdo from there you have to learn how to query pdo gud luck .
getMessage();
}
?>

Trying to pass a student key from a html form to a php file to scan a database

Basicaly having issues setting up a webpage which will taken in a student key entered by the user. This will then parse the student key to another file which will run it against a mysql backend to see what records this student already has. But can not get it working for the life of me please help I'm still a newb at this.
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("support_log", $con);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like '$_POST[stkey]'");
$result2 = mysql_query($result) or die("Error: " . mysql_error());
if(mysql_num_rows($result2) == 0){
echo("no records found");
} ELSE {
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Surname</th>
<th>Year Group</th>
<th>Student Key</th>
<th>Issue</th>
</tr>";
while($row = mysql_fetch_array($result2))
{
echo "<tr>";
echo "<td>" . $row['First_Name'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "<td>" . $row['year_group'] . "</td>";
echo "<td>" . $row['stkey'] . "</td>";
echo "<td>" . $row['issue'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close($con);
?>
After changing my where statement to:
WHERE student.STKEY like '$_POST[stkey]'");
I am no longer reciving errors from PHP but now recieving the error Query was empty which is part of my code to detect if there is no results. Though I have tested that query in phpmyadmin and it spits out results. From looking at the code does anyone have any solutions? I have also checked the parse by running an echo on the post command to ensure the data being entered was correct.
Edit: Got rid of the whole result2 check now throwing a:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\stkey_submit.php on line 24
Try $_POST['stkey'] instead of $_POST[stkey]
EDIT : if you use it in a query, it would be preferable to do :
$stkey = mysql_real_escape_string($_POST['stkey']);
$sql = "SELECT ....... like '$stkey'";
mysql_query($sql);
$result= mysql_query("SELECT student.first_name, student.surname, student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY like " . $_POST["stkey"]);
How about storing the value of stkey on a variable before including it on the query?
$stkey = $_POST['stkey'];
$result= mysql_query("SELECT student.first_name, student.surname,
student.year_group, student.STKEY, student_log.issue
FROM `student` JOIN `student_log`
WHERE student.STKEY LIKE '%$stkey%'");
You might also want to use MySqli or PDO instead of the MySql database API. Take a look at this post from Nettuts: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/

Categories