Apologies for opening what should be considered a very basic question. Please note I have coded using the mysql_query method 1000's of times thus, it is really difficult for me to make the switch but I'm finally doing it.
My 1st Problem
My 1st problem comes in simply returning a list of select statements
Example:I am trying to execute:
$sql="Select *From members";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$name = $row['name'];
}
I have read the following SO questions, and tried to implement the answers without success,
PDO equivalent of mysql_fetch_array
translation mysql_fetch_array to PDO::FETCH_NUM
I am now working with a PHP book supposed to be "one of the best for 2015/16", the book says the following regarding the above problem
Again I have tried the recommendation from the book without success
<?php
$dsn ='mysql:localhost;dbname:myDB;';
$uname = 'root';
$pword = '';
$db = new PDO($dsn, $uname,$pword);
if($db){
echo'Success';
} else {
echo'error';
}
$sql="SELECT * from members";
$results = $db->query($sql);
foreach($results as $result) {
echo $result['name'];
}
The above code gives me the message, "success" thus, I am successfully connecting to my DB but the query returns the following error:
Invalid argument supplied for foreach()
I am finding it enormously frustrating that I have to go through such lengths just to return the results from a simple select statement and am seriously considering going back to the old way, where I would have completed my assignment by now, I am turning to the SO community for help in a last attempt to get it right. Any help greatly appreciated.
I am very ashamed of posting this, but I have found the problem. Possibly it might help someone in the future.
The code with querying the DB is fine.
The Problem is with the following in line 1:
$dsn ='mysql:localhost;dbname:myDB;';
It should read
$dsn ='mysql:host=localhost;dbname=myDB;';
The If statment will always return echo success even if you are not connected thus, use try/catch
lesson learned: Always inspect your code from line 1
Related
This has probably been asked before, please feel free to link me or whatever, I just couldn't find exactly what I'm after.
It's pretty simple, I need to display the results of a search form. That part is easy and I can get that to work. What I'm having trouble with is when no results match what the user searched.
I'm fairly certain I need to just use an IF statement but I'm not very experienced with PHP and cannot figure out how to correctly display the code.
This is what I have so far:
$query = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
if (!$query)
{
echo "No results found in the database. Please go back and search again.";
}
My question is: How do I get the 'No results found...' message to display when the users search doesn't match anything in the database?
NOTE - I get very confused very quickly when it comes to trying to understand certain terms within PHP and SQL so please try to explain your answer like you would to an absolute beginner.
Many thanks in advance.
You want to show the "No results found"-message when no rows are found in the database table.
To do this, you can use below PHP and SQL code:
$sql = "SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'";
$query = $db->prepare($sql);
$query->execute();
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Note that the above answer is vulnerable to SQL injection attacks.
To prevent SQL injection attacks, it is recommended that you prepare and bind all user-submitted data, here is a better example that shows how SQL injection attacks can be prevented: (full example, including database connection)
$db = new PDO($dsn);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $db->prepare("SELECT * FROM search WHERE isbn=:isbn OR bookname=:bookname OR author=:author OR category=:category");
$query->execute([ ':isbn'=>$isbn, ':bookname'=>$bookname, ':author'=>$author, ':category'=>$category ]);
$rows = $query->fetch(PDO::FETCH_NUM);
if($rows[0]) {
// Row exists
} else {
echo "No results found in the database. Please go back and search again.";
}
Assuming you are using Mysqli ,
//connect with mysql
$conn = mysqli_connect("localhost", "user", "password", "db");
//here is the query
if($result = mysqli_query($conn,"SELECT * FROM search WHERE isbn='$isbn' OR bookname='$bookname' OR author='$author' OR category='$category'")){
if(mysqli_num_rows($result) > 0){
//mysqli_num_rows() returns the number of rows in a result .
//when it is greater than zero, it has some results
}
else{
echo "No results found in the database. Please go back and search again.";
//Do something if no results returned
}
}
//finally free the results
mysqli_free_result($result);
mysqli_close($conn);
I have a a form that pulls data from a database(mysql to be specific) and echos the data into the value section of <input> tags. It doesn't seem to be working I have coded a view section of my website to do the same thing but from a different table in my database. I use the same code to make making changes easy and if another developer works on my site in the future. Anyway it doesn't seem to be working I'm not sure why though.
The full error I get:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home/caseol5/public_html/jj/admin/news_update.php on line 9
Here is line 9 that the error is referring to:
$result = mysqli_query($link,$sql);
I know that both of those function are not null as I did:
echo $link
echo $sql
before that line after I started feting the error and they both are not null.
Here is the full code segment:
$nid = $_GET['nid'];
include ("../sql/dbConnect.php");
$sql = "SELECT * FROM jj_news WHERE news_id = $nid";
echo "<p>The SQL Command: $sql </p>";
echo "<p>Link: $link </p>";
$result = mysqli_query($link,$sql);
if (!$result)
{
echo "<h1>You have encountered a problem with the update.</h1>";
die( "<h2>" . mysqli_error($link) . "</h2>") ;
}
$row = mysqli_fetch_array($result);
$ntitle = $row['news_title'];
$ntline = $row['news_titleline'];
$ndesc = $row['news_desc'];
$nother = $row['news_other'];
I have looked into mysqli_query and I can't find anything I'm missing. I have also tired breaking the code down (and running parts of it and it gives the same error. My guess is it something small that I missed. I've looked at other question on this site that do that are a little similar but none seem to help. I've been looking at this for a while now and need another pair of eyes.
Update
As requested the contents of my dbconnect.php file:
$hostname = "localhost";
$username = "caseol5_jjoes";
$database = "caseol5_jj_site";
$password = "password1";
$link = mysqli_connect($hostname, $username, $password, $database);
$link = mysqli_connect($hostname,$username,$password,$database) or die("Error " . mysqli_error($link));
if (!$link)
{
echo "We have a problem!";
}
As clearly stated in the error message, mysqli_querydocs expects the first parameter to be a mysqli resource. In your case, this parameter is called $link but it holds a null value. A proper mysqli resource is normally obtained from connecting with the database by making use of mysqli_connectdocs
I expect the ../sql/dbConnect.php file holds the logic to connect with the database. Verify whether the $link variable is indeed initialized there. If it's not there, try to find an occurrence of mysqli_connect - maybe the resource is set to a different variable.
Without knowing what exactly is in ../sql/dbConnect.php, your problem right now is that you do not have a valid mysqli resource to use for mysqli_query.
although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.
I am starting to learn php PDO because I've read that it is more efficient and secure.
I could do the following with simple mysqli but am having trouble making it work with PDO.
PID stands for an id number.
fname stands for: first name.
lname stands for: last name.
age stands for ... age.
Basically I have an index.php that contains links from a test table called "persons" inside of the database drinks. When I click on the link which shows the fname of every row, it goes to insertcarbonated.php which is then supposed to $_GET['fname']; of the link and search up that specific row. However, my code in insertcarbonated.php is not working and I am not familiar enough with PDO to know exactly why, I would like some enlightenment on this because I literally begun learning PDO yesterday. :(
Here is my insertcarbonated.php:
<html>
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'theusername';
/*** mysql ***/
$password = 'thepass';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
/*** The SQL SELECT statement ***/
$fname = $_GET['fname'];
//is _GET even working with PDO?
$STH = $dbh-> prepare( "SELECT * FROM persons WHERE fname LIKE '$fname'" );
/***as Joachim suggested, I had actually two different variables here, however, it
did not solve the issue **EDITED** from ($DBH to $dbh)****/
$STH -> execute();
$result = $STH -> fetch(0);
//$result should print out the first column correct? which is the person's ID.
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<head>
</head>
<body>
<p><?php print $result; ?></p>
//me trying to print out person's ID number here.
</body>
</html>
As previously mentioned, I'm not sure where my error is, I get fatal error:
Call to a member function prepare() on a non-object?
and If I try to not use that function, my page is simply blank and nothing prints out.
Basically I would just like to print out different bits of information from that row (that is from it's relevant link in index.php). I would like to know how to solve this using PDO.
Here is the previous question I asked, and it was solved but not with PDO.
Previous question
You could do something like this...
try {
$dbh = new PDO("mysql:host=$hostname;dbname=drinks", $username, $password);
$fname = $_GET['fname'];
$sth = $dbh->prepare("SELECT * FROM persons WHERE fname LIKE ?");
$sth->execute( array($fname) );
$result = $sth->fetch(PDO::FETCH_OBJ); // or try PDO::FETCH_ASSOC for an associative array
}
catch(PDOException $e)
{
die( $e->getMessage() );
}
In the HTML part you can do print_r($result) and you will see the exact structure of your results.
Comments: one of the best reasons to use PDO is the automatic escaping of the dynamic user inputs, like $fname here, so you should use it. Also, with $sth->fetch($param) the $param is not the column number but the type of the fetch method PDO will use (see PHP manual). Depending the method, you can get the PID of the result by $result->PID in case of PDO::FETCH_OBJ or by $result['PID'] when using PDO::FETCH_ASSOC. I hope this helps.
this is probably the most basic question in the world, but I cannot figure it out.
I would like to simply display a users First name, and Email adress from my table. I have tried using a loop, but that was entirely worthless considering I am only selecting one row. I know this is a menial question but I could not find/remember how to do it. Thank you!
$db = mysql_connect("server","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT FirstName, EmailAddress"
. " FROM Student"
. " WHERE StudentID = '$student' ";
$result = mysql_query($sql, $db);
$num = mysql_num_rows($result);
$userinfo = mysql_result($result,$userinfo);
$student is a session variable. I want to echo the First name and email address somewhere in the page, but I cannot believe how much pain thats causing me. Thanks again!
mysql_fetch_assoc() turns a result row into an array.
$result = mysql_query($sql, $db);
$user = mysql_fetch_assoc($result);
echo $user['FirstName'];
echo $user['EmailAddress'];
It looks like you spelled address wrong, so it probably doesn't match your real column name. More importantly, your code appears vulnerable to SQL injection. You really need to use prepared statements (see How to create a secure mysql prepared statement in php?) or escaping.
To fetch a row, you must use one of the mysql_fetch functions (e.g. mysql_ fetch_ array, mysql_ fetch_ object, etc.)