PHP PDO always give only one result - php

I wrote a SQL query with PDO. DB table has 3 results with match the query. But the PDO shows only one result.
my code is this
conn.php
function connect() {
$servername = "localhost";
$dbname = "guiding_db";
$username = "user";
$password = "pass";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
_admin.php
include_once './conn.php';
function getStudentsRequests(){
$sql = "SELECT * FROM `user` WHERE signas = 'student' AND accept='0'";
$result = connect()->query($sql);
$out = $result->fetch(PDO::FETCH_ASSOC);
print_r($out);
return $out;
}
getStudentsRequests();

PDOStatement::fetch() loads a single row only. Use PDOStatement::fetchAll() to load all rows (or use a while loop):
$out = $result->fetchAll(PDO::FETCH_ASSOC);

fetch method return only one row from query. If you want all you need to use while loop or fetchAll method

fetch method return next result (one). If you wish get all results - use methods like fetchAll

Related

I'm unable to insert into MySQL using PHP (no errors are being displayed)

<?php
$q= $_REQUEST["q"];
$r = $_REQUEST["r"];
$s = $_SESSION['empid'];
$max = 0;
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$dbname = 'employeesurvey';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql1 = "SELECT QuestionID FROM question";
if(!mysqli_query($conn,$sql1)){
echo 'error2 php';
}
while($rw1 = mysqli_fetch_array($sql1)){
$Q = $rw1['QuestionID'] ;
if ($max<$Q){
$max = $Q;
}
}
$Q = $Q+1;
$sql = "INSERT INTO question VALUES (".$Q.",'".$r."',".$s.",CURRENT_DATE(),".$q.",0)";
if(!mysqli_query($conn,$sql)){
echo "Error";
}
?>
The db, table names are all correct. I'm using xmlHttpRequest.open() to pass the values to this page
the call statement is:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "gethint1.php?q=" + cid + "&r=" + question, true);
Im not getting any errors, nor the values are being inserted
Replace this line:
if(!mysqli_query($conn,$sql1)){
with these
$resultSet = mysqli_query($conn,$sql1);
if(!$resultSet){
And now replace this line:
while($rw1 = mysqli_fetch_array($sql1)){
With this one
while($rw1 = mysqli_fetch_array($resultSet)){
Reason is that you haven't executed query and stored the result set while at fetching record from result set, you are using direct query variable which is logically wrong.
why are you making a simple thing this complicated by obtaining Question id from table just use autoincrement field in your mysql table or use insert_id
and the problem is mysqli_fetch_array() function works on mysqli_query() function's output i.e. a object you are providing a string to a function which expects an object

How select from one MYSQL DB and insert it into another?

I'm running some small Updates via CRON and execute them with PHP.
Now I want to select something from DB1 and insert it into DB2
My Problem is, that these 2 DBs are on the same Server but with 2 different Users and its not possible to give 1 User permission to both DB's.
So I know this works with one user and dbconnect:
insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)
How can I do it with 2 db connects in one Loop?
Thanks
you can create two files of connection like this
<?PHP
function connect(){
$servername = "localhost";
$username = "user";
$password = "psw";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if(mysqli_connect_errno()){
echo "Error conectando a la base de datos: " . mysqli_connect_error();
exit();
}
else{
$conn->query("SET NAMES 'utf8'");
return $conn;
}
}
function disconnect($connection){
$disconnect = mysqli_close($connection);
}
?>
and in your php file and like this
require("connection.php");
$connection=connect();
require("connection2.php");
$connection2=connect2();
obviously in your connection2.php your funtion named connect2(); and in your loop you can use the two connection
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection -> query($query))){
$messageResult = "Error";
$band = false;
}
or..
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection2 -> query($query))){
$messageResult = "Error";
$band = false;
}
If u r using pdo. U declare 2 different connection.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass)
$dbh2 = new PDO('mysql:host=localhost;dbname=test', $user2, $pass)
Then u do this
$query = $dbh->prepare(select statement);
$query->execute();
$data = $query->fetchAll(); // you get array of data
$query = $dbh2->prepare(insert statement);
$query->execute()
Create 2 dB connection in two different variable and make that work .... Take value of first db in one variable and simply dump that variable into second db .... Or you can use another dB or caching dB like redis to store one time temporary base.

DELETE multiple rows in PDO

I'm a rookie in PDO and I've done some search about the issue I'm facing and I wasn't able to find any answers about it. As you can see below, I have this function:
function deleteInfo($id){
$pdo = connPDO();
$deleteInfo = $pdo -> prepare("DELETE FROM game_locais_zumbis WHERE id_zumbi IN (:id)");
$deleteInfo -> bindValue(":id", $id, PDO::PARAM_STR);
$deleteInfo -> execute();
$pdo = null;
}
After that, I have the following code:
while($row = $listInfo -> fetch(PDO::FETCH_ASSOC)){
$ids[] = $row['ids'];
}
$ids = implode(',', $ids);
deleteInfo($ids);
When I echo my $ids, I get:
1,2,3,4,5
But the DELETE function is not deleting all those five rows in my db but only the first one, like "1". When I run that exactly same DELETE function in my db, replacing the ":id" with "1,2,3,4,5", it does work! Does anybody know what's my mistake here? I appreciate any help.
I would do this:
$query = "DELETE FROM game_locais_zumbis WHERE id_zumbi in (".str_repeat("?,", count($ids) - 1)."?)";
$stmt = $conn->prepare($query);
$stmt->execute($ids);
Unfortunately you can't bind an array of elements with prepared statements. You will have to build them in the query directly.
function deleteInfo($ids)
{
$pdo = connPDO();
if (!is_array($ids))
$ids = array($ids); // if it is just one id not in an array, put it in an array so the rest of the code work for all cases
$ids = array_map([$pdo, 'quote'], $ids); // filter elements for SQL injection
$pdo->exec('DELETE FROM game_locais_zumbis WHERE id_zumbi IN (' . implode(', ', $ids) . ')');
}
Remember to pass the array to deleteInfo() instead of imploding it into a string.
This is how i have done it and it worked. I created an array and looped through it.
<?php
// set a database connection
$host = "localhost";
$user ="root";
$password = "";
$db = "pdopost";
//Set a DSN
$dsn = 'mysql:host ='.$host . ';dbname='.$db;
// Create a PDO instance
$pdo = new PDO ($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$ids=['6', '7'];
foreach($ids as $id){
$sql = "DELETE FROM posts WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$id]);
}
echo 'Deleted in the database';
?>

PDO select query return only the first row

I am new at PDO. I was trying to retrieve data from the database by using a search keyword,
but I only get the first row in which the keyword is match. It doesn't return other rows.
Here is my code::
<?php
$dsn = 'mysql:host=localhost;dbname=cois';
$user = 'root';
$password = '';
$pdo = new PDO($dsn, $user, $password);
$filmName = "shaban";
$sql= "SELECT * FROM staff_info WHERE fname = :filmName";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':filmName', $filmName, PDO::PARAM_STR);
$stmt->execute();
$total = $stmt->rowCount();
while ($row = $stmt->fetchObject()) {
echo $row->surname.'</br>';
}
Currently it return only the first row.....it prints shekidere
How can i make it print both shekidere and kimweri
Any help?
Of course it stops always on the first row. You can use foreach instead of while and use an $arrayVariable[] = CurrentRow ; to fill it next by next.

Help with mysqli and multiple queries

I've never had to use mysqli until today and cannot seem to get this right. What I want is a simple function that will accept a mysql procedure call and have it return those results.
When I started using these procedures, I noticed that the old way of querying the database, using mysql_query, would no longer get me the expected results; one procedure would successfully return and the other would not. After reading the manual and several other examples out there, I found that the reason for this odd behavior was because the results need to be buffered then cleared. I have tried several ways of doing this and have been unsuccessful.
What I have so far works if I create another instance of the mysqli object and will get me both results however, I don't think it's right that I should have to instantiate 20 different objects to get back 20 different queries.
Again, what I want here, is to have a single function that I can feed a procedure to and have the results returned back.
$mysqli = new mysqli('host','user','password','test');
$rs = $mysqli->query('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$mysqli2 = new mysqli('host','user','password','test');
$rs2 = $mysqli2->query('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}
you can make a class for this:
db.php // A db class. Call this you perform a query.
<?php
class MyConnection{
var $db_host = 'Localhost';
var $db_user = 'mYUserName';
var $db_password = 'myPassword';
var $db_name = 'mYDB';
var $connection;
function Connect(){
$this->connection = #mysqli_connect($this->db_host, $this->db_user, $this->db_password)
or
die("Error: ".mysqli_connect_error());
mysqli_select_db($this->connection, $this->db_name);
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
function Disconnect(){
mysqli_close($this->connection);
}
function ExecSQL($query){
$result = mysqli_query($this->connection, $query)
or
die('Error: '.mysqli_error($this->connection));
return $result;
}
}
?>
Implementation:
include "db.php";
$conn = new MyConnection;
$conn->Connect();
$rs = $conn->ExecSQL('CALL titles()');
while($row = $rs->fetch_object())
{
print_r($row);
}
$rs2 = $conn->ExecSQL('CALL colours()');
while($row2 = $rs2->fetch_object())
{
print_r($row2);
}
$conn->Disconnect();

Categories