I'm trying to execute two almost identical queries. But for some reason it keeps loading if I execute them both.
Here is my code:
$query = "show columns from auto_new";
$stmtColumns = $db->prepare($query);
$stmtColumns->execute();
$result = $stmtColumns->fetchAll(PDO::FETCH_BOTH);
foreach($result as $r) {
$velden .= $r["0"]. "| ";
}
$query = "show columns from auto_coc";
$stmtColumnsCoc = $db->prepare($query);
$stmtColumnsCoc->execute();
$resultCoc = $stmtColumnsCoc->fetchAll(PDO::FETCH_BOTH);
foreach($resultCoc as $r) {
$velden .= $r["0"]. "| ";
}
If I only execute one of two queries it works just fine, but both doesn't work at all.
Also tried the following with no luck:
$auto_new = 'auto_new';
$auto_coc = 'auto_coc';
$query = "SELECT * FROM information_schema.columns
WHERE TABLE_NAME =:auto_new OR TABLE_NAME = :auto_coc";
$stmt = $db->prepare($query);
$stmt->bindParam(':auto_new', $auto_new, PDO::PARAM_STR);
$stmt->bindParam(':auto_coc', $auto_coc, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_BOTH);
In both ways it keeps loading forever. What am I doing wrong?
Related
I'm having some trouble with php coding. What I want to do is following:
Create an array ($rows) and fil it with the results of a mysqli_query ($query1) --> OK
for each element in that array, replace the value of a certain key (pilot_rule_id) with the result of another mysqli_query ($query2). (the second query will return one row, since the id of the pilot table is the primary key).
So far I have
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$rows = array();
$query1 = mysqli_query($con, "SELECT * FROM pilot_time_schedule WHERE pilot_id='$id'");
while($r = mysqli_fetch_assoc($query1)) {
$rows[] = $r;
}
foreach($rows as $pilotRuleId) {
$pilotRuleId->$pilot_rule_id;
$query2 = mysqli_query($con, "SELECT name FROM pilot_rule WHERE id='$piloteRuleId'");
while($r = mysqli_fetch_assoc($query2)) {
$result[] = $r;
}
// Don't know how to continue from here
You can something like this:
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT * FROM pilot_time_schedule WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
$stmt = $con->prepare('SELECT name FROM pilot_rule WHERE id=?');
$stmt->bind_param('s', $row['pilot_rule_id']);
$stmt->execute();
// replace with the `name` returned from the above statement.
$row['pilot_rule_id'] = $stmt->get_result()->fetch_row()[0] ?? null;
}
However, you really should learn about SQL joins instead. Using SQL joins you can avoid N+1 queries to the database.
$id = "96707ac6-ecae-11ea-878d-005056bbb446";
$stmt = $con->prepare('SELECT pilot_time_schedule.*, pilot_rule.name
FROM pilot_time_schedule
JOIN pilot_rule ON pilot_rule.id=pilot_time_schedule.pilot_rule_id
WHERE pilot_id=?');
$stmt->bind_param('s', $id);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
echo $row['name']; // contains the name from pilot_rule
}
I would like to secure my requests in my code.
Today my curent functions are like this.
public function UpdatePMS($table,$data,$where) {
$ret = array();
$set_data = "";
foreach($data as $key => $value){
$set_data .= $key."= '".$value."', ";
}
if (isset($where)) {
$where = "WHERE ".$where;
}
$sql = "UPDATE ".$table." SET ".$set_data."".$where;
$sql = str_replace(", WHERE", " WHERE", $sql);
$stm = $this->db->prepare($sql);
$ret = $stm->execute();
return $ret;
}
With this way, i can select any tables, any datas, and any conditions.
For example:
WHERE id = 1 and status < 10
Or only
WHERE id = 10
Or sometimes
WHERE id = 1 and status >= 5
The content of where could change.
A kind of universal request.
Same for Delete, Update, Select, insert.
I tried to do like this, but it doesn't work.
$db = new PDO('mysql:host=localhost;dbname=asterisk','root','');
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
$ret = $stm->fetchall(PDO::FETCH_ASSOC);
Any ideas?
Frankly, you cannot use prepared statements this way. There are rules to follow. So it just makes no sense to write something like this
$table = "my_table";
$where = "WHERE id = 1";
$sql = 'SELECT * FROM :table :where';
$stm = $db->prepare($sql);
$stm->execute(array(":table" => $table, ":where" => $where));
instead you should write this code
$sql = 'SELECT * FROM my_table WHERE id = ?';
$stm = $db->prepare($sql);
$stm->execute(array($id));
Besides, you cannot parameterize table and field names, so it's better to write them as is.
so i need to make one function per different requests, right?
Honestly - yes. It will spare you from A LOT of headaches.
public function UpdatePMS($data, $id)
{
$data[] = $id;
$sql = "UPDATE table SET f1 = ?, f2 = ? WHERE id = ?";
$stm = $this->db->prepare($sql);
$ret = $stm->execute($data);
return $ret;
}
which is going to be used like
$obj->UpdatePMS([$f1, $f2], $id);
I have seperate tables full of data and I require the same data from each table. For example the first table I am selecting from has the value 3623 and the second table has the value 3852.
I am trying to get both of these values into an array to then be plotted on a graph later down the line. The code I am using can be seen below, the issue is that on the value from the first foreach loop gets added and not the second one. so I end up with just 3623 and not the 3852 as well which is an issue.
$datay1 = array();
$yes = "not-set";
$sql = "SELECT * FROM `0530-0605` WHERE SearchTerm = :yes";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}
$sql = "SELECT * FROM `0606-0612` WHERE SearchTerm = :yes";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}
print_r($datay1);
You can use UNION ALL to merge result of two query as
$sql = "SELECT * FROM `0530-0605` WHERE SearchTerm = :yes
UNION ALL
SELECT * FROM `0606-0612` WHERE SearchTerm = :yes1";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":yes", $yes);
$stmt->bindParam(":yes1", $yes);
$stmt->execute();
foreach($stmt as $row) {
$datay1[] = $row['Clicks'];
}
When I execute this query to the DB:
SELECT * FROM `task` WHERE `date_time_from` like '%0000%'
I get a few results, now I am trying to do the same with PDO and I can not manage to get any results or errors. This is what I have done:
$dbChain = 'mysql:host='.$GLOBALS['dbhost'].';dbname='.$GLOBALS['dbname'];
try{
$dbh = new PDO($dbChain, $GLOBALS['dbuser'], $GLOBALS['dbpassword']);
$sql = "SELECT * FROM task"
. "WHERE date_time_from like CONCAT('%', :dateFrom, '%')";
$a = '0000';
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
$total = $stmt->rowCount();
echo $total;
while ($row = $stmt->fetch()){
var_dump($row);
}
} catch (Exception $e){
echo 'Error'.$e->getMessage();
}
The result of this is $total = 0. Can anyone tell me what am I doing wrong?
I have also tried this:
$sql = "SELECT * FROM task"
. "WHERE date_time_from like :dateFrom";
$a = "%0000%";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':dateFrom', $a);
$stmt->execute();
Same result for $total.
bindParam escapes the "%" in the query. It will not work as you expect...
You can, however, use bindValue like so...
$sql = "SELECT * FROM task WHERE date_time_from LIKE ?";
$stmt = $dbh->prepare($sql);
$stmt->bindValue( 1, "%0000%" );
$stmt->execute();
Alternatively, if you want 0 values from a datetime column, you can just do this:
$sql = "SELECT * FROM task WHERE date_time_from = '0000-00-00'";
I am trying to do a row count, I want to count a row (nummer) and if there is more then 1 row with the same number then echo. but no matter how many rows I have in my tabel, it only returs 0
$nummer = $_GET['nummer'];
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
$result->bindParam(':n', $nummer, PDO::PARAM_INT);
$result->execute();
$rows = $result->fetchAll;
if(count($rows) >1) {
echo "1";}
else {
echo "0";
}
The following statement
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
will always return one row with the count number, so doing
$rows = $result->fetchAll;
will always return one.
You may do as
$result = $pdo->prepare("select count(*) as tot from rum where nummer=:n");
....
....
$rows = $result->fetchAll();
if($rows["tot"] > 0 ){
echo 'something'
}else{
echo 'something else'
}
just use fetch() instead of fetchAll()
$rows = $result->fetch();
if($rows[0]) >1) {
echo "1";
} else {
echo "0";
}
It looks like you're having two mistakes.
First one: If you're querying for COUNT(*) - you are getting a number of rows. For example: You're return will be a field named COUNT(*) with one row containing the number of rows found.
If you replace
$result = $pdo->prepare("select count(*) from rum where nummer=:n");
with
$result = $pdo->prepare("select * from rum where nummer=:n");
Second one:
Replace
$rows = $result->fetchAll;
With
$rows = $result->fetchAll();
fetchAll() is no property but a method.
The other way would be your query but naming the field (MySQL AS keyword) and calling $rows = $result->fetch(); afterwards and checking $rows->fieldName for the number of found rows.
Use PDOStatement::fetchColumn(). It is useful for "one-column" resultsets (which relatively often produced by queries like SELECT COUNT(...) FROM ...). Example:
$nummer = isset($_GET['nummer']) ? $_GET['nummer'] : null;
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT COUNT(*) FROM rum WHERE (nummer = :n)');
$stmt->bindParam(':n', $nummer, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchColumn();
echo $rows > 1 ? "1" : "0";