$db contains the connection to the database.
I am getting the Error in The foreach statement.
Error Message :
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number' in /home/a5057270/public_html/insert2.php:33 Stack trace: #0 /home/a5057270/public_html/insert2.php(33): unknown() #1 {main} thrown in /home/a5057270/public_html/insert2.php on line
Here's The PHP code :
$date = $_GET['date'];
$time = $_GET['time'];
$mode = $_GET['mode'];
$tfno = $_GET['tfno'];
$params = array(':date' => $date);
$query = "SELECT * FROM cabs WHERE DATE=':date' ";
if ($mode!=='' || $mode!=="") {
$query .="AND MODE=':mode' ";
$params[':mode'] = $mode;
}
if ($tfno!=='') {
$query .="AND TFNO=':tfno' ";
$params[':tfno'] = $tfno;
}
$query .="ORDER BY TIME";
$req = $db->prepare($query);
$req->execute($params);
//Build Result String
$display_string = "<article class='container box style3'><section><header><h3><u><b>Here Are The Results...!!</u></b></h3></header><div class='table-wrapper'><table class='default'><thead><tr><th>ID</th><th>Name</th><th>Description</th><th>Contact No.</th></tr></thead><tbody>";
// Getting Error in the line Below
foreach ($req as $row) {
$display_string .="<tr><td>" . $row[IDNO] . "</td><td>" . $row[NAME] . "</td><td><ul><li> Date : " . $row[DATE] . "</li><li> Time : " . $row[TIME] . "</li><li>
Train/Flight No. " . $row[TFNO] . "</li></ul></td><td>" . $row[CONTACT] . "</td></tr>";
}
$display_string .= "</table>";
that's because you are putting '' around your PDO vars...
remove them and all is good. example: make ':mode' => :mode with no '' and it will work.
$params = array(':date' => $date);
$query = "SELECT * FROM cabs WHERE DATE=:date "; //No '' here
if ($mode!=='' || $mode!=="") {
$query .="AND MODE=:mode "; //No '' here
$params[':mode'] = $mode;
}
if ($tfno!=='') {
$query .="AND TFNO=:tfno ";//No '' here
$params[':tfno'] = $tfno;
}
Related
I converted a bootgrid plugin (code snippet) from mysqli to pdo. The records are retrieved but I can not perform a search. Surprisingly, the mysqli version of the code works just fine (both retrieval and search). Running the query in mysql works just fine so not sure what I am doing wrong.
The function [block] that is generating the errors:
function getRecords($params) {
$sql = $sqlRec = $sqlTot = $where = '';
$rp = isset($params['rowCount']) ? $params['rowCount'] : 10;
if (isset($params['current'])) {
$page = $params['current'];
} else {
$page = 1;
};
$start_from = ($page - 1) * $rp;
if (!empty($params['searchPhrase'])) {
$where .= "WHERE";
$where .= "name LIKE '" . $params['searchPhrase'] . "%' ";
}
if (!empty($params['sort'])) {
$where .= " ORDER By " . key($params['sort']) . ' ' . current($params['sort']) . " ";
}
// getting all records without any search
$sql = "select * from students";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if (isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
if ($rp != -1) {
$sqlRec .= " LIMIT " . $start_from . "," . $rp;
}
$qtot = $this->conn->prepare($sqlTot);
$qtot->execute();
$queryRecords = $this->conn->prepare($sqlRec);
$queryRecords->execute();
while ($row = $queryRecords->fetch(PDO::FETCH_ASSOC)) {
$this->data[] = $row;
}
$json_data = array(
"current" => intval($params['current']),
"rowCount" => 10,
"total" => intval($qtot->rowCount()),
"rows" => $this->data // total data array
);
return $json_data;
}
Error log from the console:
Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 in ..\inc\process.php:95
Stack trace:
#0 ..\process.php(95): PDOStatement->execute()
#1 ..\process.php(27): Candidate->getRecords(Array)
#2 {main}
thrown in <b>..\process.php</b> on line <b>95</b><br />```
i use following to statement to load data form SQL the SELECT query works well until php IF is executed.
i want to use 2 ORDER BY in single statement when if statement is executed i get
Fatal error : Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'AND sca IN (?)'
at line 1' in
C:\Users\Amin\Documents\NetBeansProjects\fetch.php:34 Stack trace:
0 C:\Users\Amin\Documents\NetBeansProjects\fetch.php(34): PDO->prepare('SELECT * FROM a...') #1 {main} thrown in
C:\Users\Amin\Documents\NetBeansProjects\fetch.php on line 34
How do i solve this problem
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle' ORDER BY pdt DESC";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
if (!empty($_POST['sort'])) {
if ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") { //simplistic whitelist
$query .= " ORDER BY prs " . $_POST['sort'][0];
}
}
$stmt = $conn->prepare($query);
$params = array_merge($_POST['cate'], $_POST['brand'], $_POST['model']);
$stmt->execute($params);
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
As already mentioned by #aynber, the order by should be the last clause in your query. Thus, the correct form would be as below:
if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1' AND mca='Vehicle'";
if (!empty($_POST['cate'])) {
$query .= " AND sca IN (" . str_repeat("?,", count($_POST['cate']) - 1) . "?)";
} else {
$_POST['cate'] = []; // in case it is not set
}
if (!empty($_POST['brand'])) {
$query .= " AND product_brand IN (" . str_repeat("?,", count($_POST['brand']) - 1) . "?)";
} else {
$_POST['brand'] = []; // in case it is not set
}
if (!empty($_POST['model'])) {
$query .= " AND mdl IN (" . str_repeat("?,", count($_POST['model']) - 1) . "?)";
} else {
$_POST['model'] = []; // in case it is not set
}
$query .= " ORDER BY pdt DESC";
if (!empty($_POST['sort'])) {
if ($_POST["sort"][0] == "ASC" || $_POST["sort"][0] == "DESC") { //simplistic whitelist
$query .= ", prs " . $_POST['sort'][0];
}
}
I'm trying to create a dynamic query according to the information it gets.
When $query2 is for example: 'type' => 'PvP', 'online' => 'Premium'
And $query is: SELECT * FROM dispserveur WHERE type = :type AND online = :online
This is working,
$req = $bdd->prepare("$query");
$req->execute(array('type' => 'PvP', 'online' => 'Premium'));
But when i use the $query2 variable in the execute, it's not working.
$req = $bdd->prepare("$query"); //C
$req->execute(array($query2));
I get the same error each time.
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
This is the code,
unset($sql);
unset($sql2);
if (isset($type2) AND $type2 != "all") {
$sql[] = " type = :type ";
$sql2[] = " 'type' => '$type2'";
}
if (isset($online2) AND $online2 != "all") {
$sql[] = " online = :online ";
$sql2[] = " 'online' => '$online2'";
}
if (isset($version2) AND $version2 != "all") {
$sql[] = " version LIKE :version ";
$sql2[] = " 'version' => %$version2%";
}
$query = "SELECT * FROM dispserveur";
if (!empty($sql)) {
$query .= ' WHERE ' . implode(' AND ', $sql);
}
if (!empty($sql2)) {
$query2 = implode(', ', $sql2);
}
echo $query;
echo "<br />";
echo $query2;
$req = $bdd->prepare("$query"); //C
$req->execute(array($query2));
while ($red = $req->fetch())
{echo "$red[ip]<br />";}
Thanks for your help !
The parameter of execute() should be an associative array whose keys match that :paramName. Instead, you're using $query2 which is just a string. That's why your code isn't working.
Change:
$sql2[] = " 'type' => '$type2'";
$sql2[] = " 'online' => '$online2'";
$sql2[] = " 'version' => %$version2%";
to:
$sql2['type']=$type2;
$sql2['online']=>$online2;
$sql2['version']=>"%$version2%";
And later, change
$req->execute(array($query2));
to
$req->execute($sql2);
The beetlejuice's method is correct but it's not
$req->execute(array($query2));
to
$req->execute(array($sql2));
but
$req->execute(array($query2));
to
$req->execute($sql2);
Thank you for your quick answer :)
This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks!
Here is php
if (isset($_POST['submit'])) {
$query = 'SELECT * FROM station_tab';
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone']))
{
$query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);
} elseif (!empty($_POST['station_name'])) {
$query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
} elseif (!empty($_POST['city'])) {
$query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
} elseif (!empty($_POST['zone'])) {
$query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
} else {
echo "Choose at least one option for search";
}
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)){
echo '<br/><em>' .$row['station_name'] . '</em>';
echo '<br/>city: '. $row['city'];
echo '<br/> zone: ' .$row['zone'];
echo '<br/> Long: ' .$row['lon'];
echo '<br/> Lat: ' . $row['lat'];
}
}
}
here is error message when I add name of the city to city.
Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code:
$query = 'SELECT * FROM station_tab '; // note the space at the end
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
$query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND
} elseif (!empty($_POST['station_name'])) {
$query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['city'])) {
$query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['zone'])) {
$query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
} else {
echo "Choose at least one option for search";
}
Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table
and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this
I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.