mysql AND operator not working for passing multiple parameter - php

try {
$conn = new PDO('mysql:host=localhost;dbname=dbtable', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->prepare('SELECT * FROM table WHERE name = ' . $conn->quote($name).' AND id = '. $conn->quote($id));
$data->execute();
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo "ID : ".$row['id'].'</br>';
echo "Name : ".$row['name'].'</br>';
echo "Name : ".$row['header'].'</br>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
The above works for one parameter (name) but when i use AND operator it shows no results. URL is as given below.
http://www.mywebsite.com/page.php?id=2&name=xyz

As mentioned in the documentation, you're strongly advised to use parametrized queries, like so:
$data = $conn->prepare('SELECT * FROM table WHERE name = :name AND id = :id');
$data->bindParam(":name", $name);
$data->bindParam(":id", $id);
If this still does not work, I would suggest running a similar query directly against your database, through either phpMyAdmin or the MySQL Workbench, to verify that the query actually returns anything.

$data = $conn->prepare("SELECT * FROM table WHERE name = '$name' AND id <> '$id' ");
The above code worked for me.

Related

How to delete and update using php

Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>

mysql PDO with SELECT OR, Error!: SQLSTATE[HY093]

I have a simple search form that sends a post request to my php file, that contains the input like this "searchword=test1". I then use that with PDO to search my table for mathing data.
So far I was only searching one column, using this statement:
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword);
but now I want to search trought 3 columns (named title, extract and body). I changed my code to:
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");
and now I get an error saying "Error!: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens<br/>".
If I run the SQL statement using bash ( SELECT * FROM articles WHERE title LIKE '%test%' OR body LIKE '%elem%';), the query results return fine.
Any idea what I'm missing?
Here's my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST["searchword"])) {
$searchword = $_POST["searchword"];
$query = $db->prepare("SELECT * FROM articles WHERE title LIKE :seachword OR extract LIKE :searchword OR body LIKE :searchword");
$query->execute(array(":seachword" => "%" . $searchword . "%"));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT * FROM articles');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
You have a typo: 2 x :seachword and 2 x :searchword

Error: Unknown column 'x' in 'field list'

I'm having some trouble inputting some data into a table.
I'm retrieving some values from a form and inputting them to a table, but this error shows up every time:
Error: Unknown column 'planner_id' in 'field list'
<?php
session_start();
include 'conexion_data.php';
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$teacherid = $_POST["teacherid"];
$plannerid = $_POST["plannerid"];
$yeargroup = $_POST["yeargroup"];
$subject = $_POST["subject"];
$planner_event = htmlspecialchars($_POST["event_comment"]);
$event_date = $_POST["event_date"];
echo "$teacherid $plannerid $yeargroup $planner_event $event_date <br/><br />";
if (empty($event_date) or empty($planner_event)) {
echo "One of the fields was left blank! <br />";
} else {
$sql = "INSERT INTO subject_directorio (planner_id, teacher_id, subject, yeargroup, date, comment ) VALUES ('$plannerid', '$teacherid', '$subject', '$yeargroup', '$event_date', '$planner_event')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
/* header('Location: user_area.php'); */
echo "Data was inputed to DB";
mysqli_close($con);
}
}
?>
It's very straight
while you are getting this type error :{Error: Unknown column 'planner_id' in 'field list'}
Troubleshoot first step will be Just Describe The Table [subject_directorio]
Desc subject_directorio and check planner_id is exist or not. According to to the error
subject_directorio not holding any column called as planner_id
Hope it helps!!
It's self explanatory that your table doesn't have a column planner_id. Even if you see that it has, you may have trialing spaces before or after planner_id in the column name. Check carefully.
Database
You are using wrong way how to connect to database and fetch its data.
Because you database may be hacked using SQL Injection
The right way how to do this is:
Using PDO
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
For error catching:
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
And data fetching:
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Using Mysqli
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
And your problem
I think problem is in your query and binding params to it.So try to use proper way as I shown you, and then show us results.
SQLFiddle

SQL UPDATE query executes correctly via MySQL Workbench but not via PHP

I have the following SQL query:
UPDATE uploads SET UserName='Test2', UserEmail='Test2', UploadCount='4'
WHERE Country = 'Algeria'
When I run this query via MySQL workbench it executes fine.
I am trying to run this via a website / PHP however, and am attempting to execute the query in the following way:
$sql = "UPDATE uploads SET UserName='$user_data[name]', UserEmail='$user_data[email]', UploadCount='$user_data[FilesUploaded]' WHERE Country = '$country'";
echo $sql;
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
The SQL query is being built via variables here, however I copy / pasted the echo of $sql into workbench to check that there were no syntax errors creeping in, the echo of $sql is what I pasted above.
When I run it via the web application, I get 0 row affected and the UPDATE is not made, where am I going wrong?
Thank you
UPDATE: A new paramatarized version of the PDO:
$sql = "UPDATE uploads SET ";
$sql .="UserName = :name,
UserEmail = :email,
UploadCount = :FilesUploaded";
$sql .=" WHERE Country = '$country'";
try
{
$pdo = new PDO('mysql:host=localhost; dbname=db01', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":name", $user_data['name']);
$stmt->bindParam(":email", $user_data['email']);
$stmt->bindParam(":FilesUploaded", $user_data['FilesUploaded']);
$stmt->execute();
# Affected Rows?
echo $stmt->rowCount(); // 1
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
It looks like you're trying to insert information from an array while it's in quotes. Try this:
$sql = "UPDATE uploads SET UserName='".$user_data['name']."', UserEmail='".$user_data['email']."', UploadCount='".$user_data['FilesUploaded']."' WHERE Country = '$country'";

problem with select statement mysql

This has annoyed me for a while now. I am trying this query in phpmyadmin.
select `id` from `users` where `fb_id` = 507292797 limit 1
This returns the value 13, so why doesn't this work:
$sql = "select `id` from `users` " .
"where `fb_id` = :fb_id " .
"limit 1";
try
{
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':fb_id', $fb_id2, PDO::PARAM_INT);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
$stmt->closeCursor();
}
catch (Exception $e)
{
die ($e->getMessage() );
}
echo "id: " . $fb_id2 . " var_dump: " . var_dump($user);
exit();
This returns:
id: 507292797 var_dump: bool(false)
When var_dump should return $user['id'] = 13
Can somebody see what I am doing wrong here?
ps. here is my db connection function if that matter
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
$driver_options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8' );
try
{
$this->db = new PDO($dsn, DB_USER, DB_PASS, $driver_options);
You are doing things in this order :
Preparing the statement
Binding the variables
Trying to fetch data from the statement
Executing the statement
The two last steps should be in the inverse order : you must execute the statement before you can fetch data (that's obtained by executing it).
Basically, instead of using this :
// fetch, then execute ???
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->execute();
You should use that :
// Execute, **then** fetch
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Looks like you are fetching before executing?

Categories