Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to PDO and am attempting to convert my existing PHP/MYSQL code to meet PDO standards.
The problem i am having is I can connect to the database but no results are being shown and no errors are being displayed.
This is my database:
$db2 = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', 'USERNAME', 'PASSWORD');
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db2->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
I am using
include 'db.php';
to include the above database details in my main PHP script.
My main script using the following as a select statement to display the rows which match the criteria:
<?
foreach($db2->query('SELECT view_invoice FROM user_info where username = "$timeapp_username"') as $inrow) {
$inrow['view_invoice']; //etc...
}
?>
On running this I get no errors but no results displayed. I cannot spot what I am doing wrong. Can anyone advise what I am doing wrong here?
The query function is unsafe and should be used only for queries that will not return data, like UPDATE, DELETE, INSERT...
To make safe and working SELECT queries, prepare your query with the PDOStatement. See:
//Example querystring
$id = $_GET['id'];
try{
//Instantiate PDO
$pdo = new PDO('dsn', 'user', 'password');
//Create the statement
$statement = $pdo->prepare("SELECT * FROM `my_table` WHERE `id`=:id");
//Now you can bind values to the statement. This will automatically escape the values
//Defines the type of the value that you'll bind (optional)
$data_type = (is_numeric($id)) ? PDO::PARAM_INT : PDO::PARAM_STR;
//Replace the :id in the query by the value retrieved from the querystring
$statement->bindValue(':id', $id, $data_type);
//Now, let's execute our statement
$statement->execute();
//If the query has returned any rows, we can iterate over it
if ($statement->rowCount() > 0)
{
foreach ($statement->fetchAll() as $result)
{
//Now you can retrieve the values using the defined fetch method.
//Example with associative fetch mode:
echo 'My name is '.$result['name']."!";
echo '<br />';
}
}
else
{
//No results found
}
} catch (PDOException $pe){
die("An error has occurred: ".$pe->getMessage());
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Currently, I have one table in my database called 'factory'. In this table, there are two columns, 'Fac_ID' and 'Fac_Name'. Now, I want to create a function to add some new factory to the table 'factory'.
The value of 'Fac_ID' and 'Fac_Name' must be same, which mean when I want to add factory 'F09', the value of Fac_ID and Fac_Name must be same which is 'F09'.
When I used to connect with MYSQL database (PDO), the addition is successful. BUt when i change to MSSQL (PDO),
" Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\ebooking\add_factory.php:24 Stack trace: #0 C:\xampp\htdocs\ebooking\add_factory.php(24): PDOStatement->bindParam(':Fac_ID', 'F11')"
Here is my code for add_factory.php
<?php
require_once "configPDO.php";
if(isset($_POST['Submit'])) {
$Fac_ID = $_POST['Fac_ID'];
// checking empty fields
if(empty($Fac_ID)) {
if(empty($Fac_ID)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
$query = $conn->prepare($sql);
$query->bindParam(':Fac_Name', $Fac_ID,);
$query->bindParam(':Fac_ID', $Fac_ID,);
$query->execute();
//display success message
header("Location:factory.php");
}
}
?>
and here is my configPDO.php
<?php
$servername = 'xxx.xx.xx.xxx';
$username = 'xx';
$password = 'xxxxxx';
$dbname = 'xxxx';
try {
$conn = new PDO("sqlsrv:Server=$servername;Database=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error) {
$error->getMessage();
}
?>
Can I know what the problem? the input at HTML to add the factory is 'Fac_ID'
in the following query
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_Name)";
you are using :Fac_Name twice instead you should use the following
$sql = "INSERT INTO factory(Fac_Name, Fac_ID) VALUES(:Fac_Name, :Fac_ID)";
and if you need to set the same value for the name and id you should ommit the following line
$query->bindParam(':Fac_ID', $Fac_ID,);
since you are trying to bind data to a parameter that doesnt exist in your query
the following statement is sufficent in your case
$query->bindParam(':Fac_Name', $Fac_ID,);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So basically I got this code right here:
<?php
include_once 'dbconfig2.php';
$con = new DB_con();
$table = "users";
if(isset($_GET['profile_id']))
{
$sql=mysql_query("SELECT * FROM users WHERE user_id=".$_GET['profile_id']);
$result=mysql_fetch_array($sql);
}
?>
I am clueless as to how I would make it so if the user_id is not existent in the records, they cannot view their profile but it leads them to another messsage or piece of code.
If the user_id doesn't exist, there won't be any rows in the result. When you try to read a row with mysql_fetch_array(), it returns FALSE. So you can simply test $result:
if (!$result) {
die("Invalid profile ID");
}
Try to use prepared statements using mysqli, in order to avoid sql injection.
By way of example:
$mysqli = new mysqli("localhost", "root", "root", "test");
if ($mysqli->connect_errno) {
echo "connect_error". $mysqli->connect_error;
}
$id = $_GET['profile_id'];
$result = $mysqli->prepare('SELECT name FROM users WHERE user_id = ?');
$result->bind_param("i", $id);
$result->execute();
$result->bind_result($col1);
$result->fetch();
$is_valid_profile = (!$col1) ? 'Invalid profile' : 'Valid profile';
echo $is_valid_profile;
$result->close();
http://php.net/manual/en/mysqli.prepare.php
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I made a new table , everything worked.
CREATE TABLE IF NOT EXISTS logdata (
email varchar(30),
password varchar(20),
username varchar(15),)
Inserted the id auto increment code
,and some data :
INSERT INTO logdata(email,password,username,id) VALUES('test#test.org','testtest1','test',' ')
Everything worked here. When I try to output the data i dont get any results (except "ERROR"). I have no idea why.
<?php
error_reporting(E_ALL);
// here is where I set the connection , everything is working here
if(mysqli_connect_errno()){
echo "Could not connect to the database <br /><br />";
echo mysqli_connect_error();
exit();
}
$dostuff="SELECT * FROM logdata";
$query = mysqli_query($db_conn, $dostuff);
if($query == TRUE) {
echo "Succes!";
}
else{
echo "ERROR ";
echo mysqli_error($db_conn);
}
?>
In order to query something in your database, you have to provide a query to it. Your query variable is an empty string!!
$dostuff="";
It should have some SQL statements, like e.g:
$dostuff="SELECT * FROM logdata";
Or whatever.
UPDATE
I believe that using === to test the result will fail because the mysqli_query returns a mysql_result object, according to the docs:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So if its succeful it won't be === TURE for your SELECT statement and it will have no error. Your query is fine, just try this:
if ($query = mysqli_query($db_conn, $dostuff)) {
echo "Success!";
}
else {
echo "ERROR ";
echo mysqli_error($db_conn);
}
It should works.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have new to PHP programming and looking to create access a database I created. I have been able to get a successful connection going between PHP and my database, but the problem arises when I try to run a simple query.
I get the dreaded message mysqli_query() expects parameter 1 to be mysqli. I have seen numerous issues on this throughout the internet. I still am unable to resolve my situation. Can someone please address my code here:
$mysqli= mysql_connect($hostname,$username,$password,'japanesewords')
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
mysqli_query($mysqli, 'SELECT * FROM japanesedefinition') or die(mysql_error($mysqli));
Why don't you use PDO?
<?php
try {
// config
$dsn = 'mysql:dbname=japanesewords;host=127.0.0.1;charset=utf8';
$username = 'root';
$password = '';
$options = array(
// necessary for rowCount() on SELECT
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
// for catching SQL errors as PDOException
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// default fetch mode is used for iterating PDOStatement by foreach()
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
// connect
$pdo = new PDO($dsn, $username, $password, $options);
// execute SQL
$stmt = $pdo->query('SELECT * FROM japanesedefinition');
// check row count
if (!$stmt->rowCount()) {
throw new Exception('no data');
}
// fetch results and display
echo "<p>\n";
foreach ($stmt as $row) {
printf("foo: %s; bar: %s;<br />\n", $row->foo, $row->bar);
}
echo "</p>\n";
} catch (Exception $e) {
printf("<p>%s</p>\n", $e->getMessage());
}
I don't know whether you're japanese or not, remark the summary in Japanese for connectiong to MySQL with PHP.
http://qiita.com/mpyw/items/b00b72c5c95aac573b71
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have this news system but I can't figure out how to do it like this: news.php?id=1 then it will output the news id 1. Please help.
I have this so far:
<?php
include_once('includes/config.php');
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
if(isset($_GET['id']));
echo $res['body'];
}
?>
It connects to the database (details are stored in the config).
the parameters after the ? in the URL are GET items. Use this:
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
// Rest of your code
}
<?php
include_once('includes/config.php');
// see if the id is set in the URL (news.php?id=)
if(isset($_GET['id'])) {
// get the ID from the URL
// to make it safer: strip any tags (if it's a number we could cast it to an integer)
$id = strip_tags($_GET['id']);
// don't use SELECT *, select only the fields you need
$sql = mysql_query("SELECT body FROM news WHERE id=".mysql_real_escape_string($id));
while($row = mysql_fetch_assoc($sql)) {
echo $res['body'];
}
} else {
echo 'please select an article';
}
I would recommend you get away from using the mysql functions and use mysqli instead, as mysql is depreciated and you'll have to learn mysqli or PDO anyway.
Edit: updated code per comments
Firstly lets dissect your current code, to see where your going wrong.
<?php
include_once('includes/config.php');
/*
$id is not set anywhere before its used so this if statement will not fire,
if you are attempting to get this $id from a url parameter then you need
to set it first from $_GET['id'] global
*/
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
/*
This piece of code will fire but where is $sql set?
The mysql_query() function expects a string containing your sql query
so the subsequent lines of code will fail because of this
*/
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
//this block is in the wrong place
if(isset($_GET['id']));
echo $res['body'];
}
?>
The idea is to get the user input E.G the $_GET['id'] from the url first, check the value is what your looking for, and then build your query.
As the mysql_* functions are deprecated I will show you an example using PDO. Though you can use mysqli, BUT you must always use prepared query's whenever user values come into contact with your database. This is to stop nasty/accidental sql injections.
<?php
// make the connection to the database using PDO
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=the_awsome_db', 'yourusername', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
exit('Sorry there is a problem with the database connection :' . $e->getMessage());
}
// sanitize user input - expecting an int
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if (is_numeric($id)) {
// now lets query the database with the param id from the user
// prepare the query, using a placeholder
$stmt = $db->prepare('SELECT body,
some_other_column
FROM news
WHERE id = :placeholder_id');
// bind the placeholder with the value from the user
$stmt->bindParam(':placeholder_id', $id);
// execute the prepared query
$stmt->execute();
// fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// result not empty - display
if (!empty($result)) {
// display your result, use print_r($result) to view the whole result set if unsure
echo $result['body'];
} else {
// no matching id found in the db, do something
echo 'No results found';
}
} else {
// do something as user input is not a number
exit(header('Location: ./index.php'));
}
?>
Hope it helps, if your unsure of getting parameters from the user you may need to look up some more tutorials and get the hang of that first before dabbling with databases and all that good stuff.