Why is the server rejecting my PDO query? - php

I've been trying to write a simple search and display site with a drop down menu, I've tried using mysqli and PDO and I'm not getting the results. I've just checked the server log in cpanel and found that the access has been denied to the results page. The access must be all right for the drop down page as it is populating the drop down list. I can't see why it is being stopped. The server is running PHP 5.3.27 and MYSQL 5.5.36.
This is the drop down.
<form action="search3.php" method="post" >
<?php
$mysqli = new mysqli('localhost','user','password','engraved_stamps');
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$query = "SELECT DISTINCT Country FROM engravers ORDER BY Country";
$result = $mysqli->query($query);
?>
<select >
<?php
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['Country']}\">";
echo $row['Country'];
echo "</option>";
}
$mysqli->close();
?>
</select>
<input type="submit" name="dropdown" />
</form>
This is the results page (action for restul) (called Search3.php)
<?php
$hostname = "localhost";
$user = "user";
$password = "password";
$connection = mysqli_connect($hostname, $user, $password,);
if(!$connection){
echo"Could not connect to server";
};
mysqli_select_db($connection,'engraved_stamps');
if(!mysqli_select_db($connection,'engraved_stamps')){
echo"could not connect to database";
};
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "none";
}
$sql= "SELECT * FROM engravers WHERE Country = :Country";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->Country;
}
$mysqli->close();
?>

I think PDO and mysqli are different PHP extensions. You should choose only one thing to deal with your work.
e.g., you can use mysqli only, or PDO.
For more information about PDO, see: http://php.net/manual/en/pdo.construct.php

You are mixing two entirely different database extensions:
MySQL Improved Extension (aka mysqli):
$mysqli = new mysqli(...)
^^^^^^
PHP Data Objects (aka PDO):
$stmt->bindParam(':Country', $Country, PDO::PARAM_STR);
^^^
Despite your question title and tags, your code seems to use mysqli entirely. You'll just need to get rid of the PDO bits.
You're also using some undefined variables:
$stmt = $pdo->prepare($sql);
^^^^
You're apparently not getting the corresponding error messages, which suggests you haven't configured your PHP development box to do so. As soon as you do it, you'll be possibly warned of some other issues.

Sorry abas_rafiq. the comments only allow a certain number of characters.
Here is the structure:
CREATE TABLE IF NOT EXISTS engravers (
Key int(10) NOT NULL AUTO_INCREMENT,
StampImages text NOT NULL,
Images text NOT NULL,
Country text NOT NULL,
Year int(4) NOT NULL,
Description text NOT NULL,
SGNumber text NOT NULL,
ScottNumber text NOT NULL,
Engraver1Surname text NOT NULL,
Engraver1OtherNames text NOT NULL,
Engraver2Surname text NOT NULL,
Engraver2OtherNames text NOT NULL,
Engraver3Surname text NOT NULL,
Engraver3OtherNames text NOT NULL,
Designer1Surname text NOT NULL,
Designer1OtherNames text NOT NULL,
Designer2Surname text NOT NULL,
Designer2OtherNames text NOT NULL,
Printer text NOT NULL,
Notes text NOT NULL,
PRIMARY KEY (Key),
UNIQUE KEY Key (Key)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=91 ;
They were not all "Not Null" when I set it up but I see they are now.

<?php
try {
//here add user and password and database please be sure u have used correct one
$dbh = new PDO("mysql:host=localhost;dbname=engraved_stamps",'root','');
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php
$STM = $dbh->prepare("SELECT * FROM engravers WHERE Country = :Country");
if(isset($_POST['dropdown'])){
$Country = $_POST['dropdown'];
}else{
$Country = "name";//here you can assing % too for value of any if u need tell me to recode, NOTE here now the value u have assign is (name) is the record value on ur engravers table for column of Country.
}
$STM->bindParam(':Country', $Country, PDO::PARAM_STR);
$STM->execute();
$row= $STM->fetchAll();
if(count($row)){
foreach($row as $data){
echo $data['Country'] . "<br />";// here country is the column of ur table u can echo other columns too
}
}else {
echo 'no row found';
}
?>

Related

Error SQLSTATE[HY093]: Invalid parameter number: in php PDO statement

im a newbie in php and im facing this problem...i get with it 3 days and im going mad... ;). Im trying to implement a table with users of a web application. So i have to check that the user doesnt exist.
My sql table:
DROP TABLE users;
CREATE TABLE users (
idUser INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
mail VARCHAR(45) NOT NULL UNIQUE,
name VARCHAR(45) NOT NULL,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
role enum ("admin", "user"),
state BOOLEAN,
forgotpass VARCHAR(32) NOT NULL
);
Also this code works ( test if the user already exists in the table):
//$query="SELECT mail FROM proba.users WHERE mail='{$correu}'";
$sql = 'SELECT * FROM users WHERE mail = :mailparam';
//$sql = 'SELECT * FROM users';
$stmt = $con->prepare($sql);
// 2. execute to insert a row
// with an associative array
$stmt->execute(
array(':mailparam'=>$correuFormulari)
);
// 3. get all rows
$rows = $stmt->fetchAll();
foreach ($rows as $rowActual) {
echo $rowActual['mail'] . "<br>";
echo $rowActual['password'] . "<br>";
}
But following the same logic i cant insert an element:
if(count($rows) > 0){
echo "L'usuari ja existeix";
echo "<p><a href='registreUsuari.php'>Torna</a></p>";
} else{
echo "Usuari no trobat. Passem a insertar";
//INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES ("p#gmail.com", "pepe","user", "pepito", current_Time,"forgotpass");
$user="admin";
$sqlinsert = 'INSERT INTO users (mail, password, role, name,forgotpass) VALUES (:mail, :passwordform,:usuari, :nomFormulari,:forgotpass)';
//$sql = 'SELECT * FROM users';
$stmtinsertar = $con->prepare($sqlinsert);
// $stmt = $con->prepare("INSERT INTO users (mail, password, role, name, created_at,forgotpass) VALUES (:mail, :password,:user, :nomFormulari, :data,:forgotpass)");
/* $stmtinsertar->bindParam(':mail', $correuFormulari);
$stmtinsertar->bindParam(':password', $passwordFormulari);
$stmtinsertar->bindParam(':user', $user);
$stmtinsertar->bindParam(':nomFormulari', $nomFormulari);
//$stmt->bindParam(':data', $data);
$stmtinsertar->bindParam(':forgotpass', "forgotpass");
INSERT INTO users (mail, password, role, name,forgotpass) VALUES ("hola#g,aoƱ", "pepe","user", "pedro","forgot")
*/
try
{
//$stmtinsertar->execute();
$stmt->execute(
array(':mail'=> "$correuFormulari",
':passwordform'=> "$passwordFormulari",
':usuari'=> "$user",
':nomFormulari'=> "$nomFormulari",
':forgotpass'=> "forgotpass")
);
}
catch(PDOException $e)
{
handle_sql_errors($selectQuery, $e->getMessage());
}
echo "S'ha creat l'usuari";
//header('Location: '.'login.php');
// $stmt->close();
}
I enter in the correct if, but i cant insert into the table....
The error shows something like:
pepekjjp#gamil.comConexio : object(PDO)#2 (0) { } hoola0Usuari no trobat. Passem a insertar
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
As you can read in the code i also tried to use bind->Params....
Any help would be apreciated.
Also would like to know, which form of executing PDO is preferred, using bindParameter or using an array.
Thanks in advance

Comparing SQL table to $_SESSION['user'] and printing current user info

First off I'm very new to coding in general. I have an sql-database with table:
CREATE TABLE "users" (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`name` VARCHAR NOT NULL,
`username` VARCHAR NOT NULL UNIQUE,
`email` VARCHAR NOT NULL,
`password` VARCHAR NOT NULL,
`biography` VARCHAR NOT NULL,
`img` VARCHAR
);
I wish to compare users['id'] to $_SESSION['user'] and print out all information for current user in a profile page. As of right now my code is:
$query = 'SELECT * FROM users WHERE id';
$statement = $pdo->query($query);
if (!$statement) {
die(var_dump($pdo->errorInfo()));
}
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
}
What I'm lacking is where I compare the users['id'] to $_SESSION['user'] and I'm unsure how to specifically code for that.
Any suggestions?
This is how you can do it:
$sth = $dbh->prepare('SELECT * FROM users WHERE id = :id');
$sth->bindParam(':id', $_SESSION['user']);
$sth->execute();
and then iterate the results.
There are lots of things that seem to be undone.
Your sql query seems to be incomplete.
SELECT * FROM users WHERE id='$user_id'
You are not initializing PDO object.
$pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8mb4', 'db_username', 'db_password');
Complete code snippet :
<?php
session_start();
$user_id=$_SESSION['user_id'];
$pdo = new PDO('mysql:host=localhost;dbname=db_name;charset=utf8mb4', 'db_user', 'db_pass');
$user_id=1;
$query = "SELECT * FROM engineers WHERE id='$user_id'";
$statement = $pdo->query($query);
if (!$statement) {
die(var_dump($pdo->errorInfo()));
}
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row['name'];
echo $row['username'];
echo $row['biography'];
}
?>
On the other hand use $_SESSION['user_id']=$id to set the session.

Why only some mysqli queries work?

I am facing a problem with mysqli select queries.
The table I am using is called participant and has the following fields:
id int(11) AI PK
name varchar(255)
surname varchar(255)
birth varchar(32)
sex varchar(32)
email varchar(255)
telephone varchar(32)
club varchar(255)
startingGroup int(2)
This is a PHP file (called select.php):
$connection = mysqli_connect("localhost", "$user", "$pass", "$db_name");
$query = "SELECT id, name, surname FROM participant WHERE NOT 0";
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!mysqli_query($connection, $query)) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
$result = mysqli_query($connection, $query);
$arr = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
}
mysqli_close($connection);
echo $json_info = json_encode($arr);
which is later called by AngularJS in:
$http.post("select.php").success(function(data){
console.log(data);
$scope.newparticipants = jsonFilter(data);
console.log($scope.newparticipants);
});
The value returned by the first console.log is 'undefined' and by the second "". When I change my query to select only 'id' the whole thing works and data is visible. Any guess why it is so?
It occurred that in the database there were some diacritical marks coded in utf8_general_ci. I didn't have a clue on what's going on, because some queries responded correctly, some not. Selecting ids from particular range I was receiving a correct result. Selecting a range beside - I was getting undefined. I found it very hard to detect that the problem was with encoding(only some rows contained these diacritical marks).
If you are in a similar situation - check if your database has some non-standard encoding. If so define it in your code, just after opening a database connection, for example:
(procedural style)
mysqli_set_charset($connection,"utf8");
(object-oriented)
$mysqli->set_charset("utf8")
Thank you all for trying to resolve this problem.

Inserting values into a table with a PHP-variable name

I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php

mysql update query (containing 'where' syntax) not working

I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.

Categories