So I have this piece of code that is not returning anything (the echo returns nothing and should be returning two rows):
<?php
include "connection.php";
$cliente = $_POST["cliente"];
$select = "SELECT CLIENTE, NOMCLI FROM CLIX1 WHERE NOMCLI LIKE ? ORDER BY NOMCLI";
$stmt = odbc_prepare($con, $select);
//preparing the array for parameter
$prep_array = array();
$prep_array[] = "'%$cliente%'";
$rs = odbc_execute($stmt, $prep_array);
$nombres = array();
$clienteIDS = array();
//if prepare statement is successful
if($rs)
{
$i = 0;
while($row=odbc_fetch_array($stmt))
{
$cliente_id = trim($row["CLIENTE"]);
$nombre = utf8_encode(trim($row["NOMCLI"]));
$nombres[$i] = $nombre;
$clienteIDS[$i] = $cliente_id;
$i++;
}
echo json_encode($nombres) . "|" . json_encode($clienteIDS);
}
else
{
echo "error";
}
odbc_close($con);
?>
I know the problem is not the parameter pass on the odbc_execute() because even if I do this, it doesn't return anything(with %mich% it should display two rows):
$rs = odbc_execute($stmt, array("%mich%"));
Do you see anything wrong in this code?
Please let me know and thanks in advance.
UPDATE ------
I made the changes on the code that were suggested on the answer below and I am getting a new error now:
Warning: odbc_execute(): Can't open file %mich%
Where mich is the text entered to search on the database.
I found the following that may relate: ODBC prepared statements in PHP
$prep_array = array();
$prep_array[] = "'%$cliente%'";
$rs = odbc_execute($stmt, $prep_array);
I think the Double Quotes might be causing an issue.
Related
So I made a query which returns many restaurants and I put them in a variable $row:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
When I try to run my code, it prints Array to string conversion.
The problem appears in this line:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
I searched about the error and I understand but I tried many resolutions and didn't solved the problem.
can someone help please?
You should do like the following
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
Try For PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];
The problem is in this statement
$idRestaurant = $stmt->fetch();
Have you tried $idRestaurant = $stmt->fetch()[0];?
You can actually check what's coming into $idResturant by checking it via var_dump
var_dump($idResturant)
Check this:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
To do this:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
I am trying to update a file OPPSHEDT with a priority and reason code. It seems the code gets stuck in the foreach loop. It gets to SQL with the Count I get the echo of the selstring on my browser then I do not get the echo of $Count and the update is not done. I'm not quite sure if I'm not connecting and doing the actual SQL on the Count or not. Is there anyway to tell what is going on here?
<?php
require_once ('C:/wamp/db/login.php');
// Try to connect to database
try
{
$db = new PDO($db_hostname, $db_user, $db_pass);
}
catch (PDOExcepton $e)
{
echo $e->getMessage();
exit();
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (is_array($_POST['line']))
{
$ohord = $_POST['shedord'];
$ohbord = $_POST['shedbord'];
$date1 = $_POST['sheddat'];
$type = $_POST['shedtyp'];
$prty1 = $_POST['shedpty'];
$resn1 = $_POST['shedrsn'];
foreach($_POST['line'] as $line_no)
{
$type1 = $type[$line_no];
$type2 = substr($type1, 0, 1);
$selstring = "Select Count(*) From LPCUSTTST.OPPSHEDT where sheddat = '$date1[$line_no]' and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring;
$s = $db->prepare("$selstring");
$s->execute();
echo $Count;
if($Count > 0)
{
// Update data into detail
$selstring1 = "UPDATE LPCUSTTST.OPPSHEDT SET SHEDPTY = '$prty1[$line_no]', SHEDRSN = '$resn1[$line_no]' where sheddat = $date1[$line_no] and shedtyp = '$type2' and shedord = '$ohord[$line_no]' and shedbord = '$ohbord[$line_no]'";
echo $selstring1;
$s = $db->prepare("$selstring1");
$s->execute();
}
}
}
?>
Thank You
Your first SQL statement contains date1[$line_no] while your second contains $date1[$line_no]. You can make things much easier (and safer) by using parameterized queries instead.
Edit: You modified your post to include the missing dollar sign but my suggestion to use parameterized queries still stands.
$selstring = 'SELECT COUNT(*) as total
FROM LPCUSTTST.OPPSHEDT
WHERE sheddat = :sheddat
AND shedtyp = :shedtyp
AND shedord = :shedord
AND shedbord = :shedbord';
$stm = $db->prepare($selstring);
$stm->execute(
array(
'sheddat' => $date1[$line_no],
'shedtyp' => $type2,
'shedord' => $ohord[$line_no],
'shedbord' => $ohbord[$line_no]
)
);
I do not get the echo of $Count and the update is not done
In your code you do echo $Count; but $Count is never defined. You need to fetch the value (I added total to the above SQL):
$row = $stm->fetch(PDO::FETCH_ASSOC);
$count = $row['total'];
heres my code
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
foreach ($studId as $ch){
echo $ch."<br>";
}
}
//the result of this is like this
c-1111
c-1112
c-1113
// but i want to know their names
i have a function to get the studinfo shown below. how would i apply/insert this in the above code to get the names of those stuid's..pls help
function getuserinfo($ch){
$info_select = "SELECT `$ch` FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
$fname = getuserinfo('fname');
$lname = getuserinfo('lname');
$mname = getuserinfo('mname');
This is wildly dangerous as is, but here is the basic idea:
Your current query inexplicably fetches the student id where student id equals the passed value. So that looks like it is just trying to verify, but it is unnecessary. You want to return all info, then replace the first $ch with just * to fetch all...
function getuserinfo($ch){
$info_select = "SELECT * FROM `tbl_student` WHERE `studId`='$ch'";
if ($query_get = mysql_query($info_select)) {
if ($result = mysql_result($query_get, 0, $ch)) {
return $result;
}
}
}
You call it by passing the id:
getuserinfo($ch);
You can then access all student info for the row. try var_dump(getuserinfo($ch)) to see what's returned if this makes no sense.
But you are just fetching RAW from $_REQUEST with absolutely no cleansing. You are wide open to attack this way.
Switch to PDO or mysqli and use prepared statements. This answer is just to explain how ot get the info. In no way do I condone the use of these deprecated methods as is.
edit
As per your comment, you need to access the result to do something like that...
if(isset($_POST['select'])){
$studId = $_REQUEST['studid'];
$where = "";
foreach ($studId as $ch){
$where .= "studId = '$ch' OR";
}
if(strlen($where) > 0)
{
$where = substr($where, 0, -2);
$result = $mysqli->query("SELECT studId, CONCAT(fname, " ", mname, " ",lname) AS name FROM tbl_student WHERE $where");
while ($row = $result->fetch_assoc()) {
echo $row['name'].'<br>';
}
}
}
...again, sanitize the input. It's not being done in this example. This is just to give an idea
I am using the JQuery Validation Plugin. I got the remote function working with the default php file.
I modified the php file to use my own version but mysql is returning
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/fastbluf/syatch/module/1.func.php on line 15
My PHP Code is the following. All my syntax looks correct.
<?php
// Last Edited: 4/23/12
$conn = mysql_connect('localhost','hidden','hidden') or die('Iam dying');
$rs = #mysql_select_db( "hidden", $conn) or die( "Err:Db" );
$do = $_REQUEST['do'];
$email= $_REQUEST['email'];
$user= $_REQUEST['user'];
function checkInfo($do,$email,$user){
switch ($do) {
case 1:
$sql = "select * from User_Base where Email_Address = $email";
$results = mysql_query($sql). mysql_error();
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
$valid="false";
} else {
$valid="true";
}
break;
case 2:
//not yet
break;
}
return $valid;
}
echo checkInfo($do,$email,$user);
?>
The problem is that you're appending to your result, causing it to no longer be a valid result.
$results = mysql_query($sql). mysql_error();
Try changing this to be something like this:
$results = mysql_query($sql) or die(mysql_error());
Your query should also be changed to quote the email address, and the address should be escaped to prevent attacks (SQL Injection):
$email = mysql_real_escape_string($_REQUEST['email']);
$sql = "select * from User_Base where Email_Address = '$email'";
Fix your query to
$sql = "select * from User_Base where Email_Address = '".$email."'";
i'm trying to figure this out for days and i can't find what the error might be.
This is my code:
<?php
$page = isset($_POST['page']) ? intval($_POST['page']) : 1;
$rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
include 'conn.php';
class get_data extends connection{
public function __construct($page,$rows){
$s_page=mysql_real_escape_string($page);
$s_rows=mysql_real_escape_string($rows);
$this->get_all($s_page,$s_rows);
}
public function get_all($page,$rows){
$this->connect_to_db();
$tablename = $this->define_table_name();
$offset = ($page-1)*$rows;
$result = array();
$rs = mysql_query("select count(*) from $tablename");
$row = mysql_fetch_row($rs);
$result["total"] = $row[0];
$startq="select * from $tablename limit $offset,$rows";
$rs = mysql_query("select * from $tablename limit $offset,$rows");
$items = array();
while($row = mysql_fetch_object($rs)){
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
}
}
$getdata=new get_data($page,$rows);
?>
The Output is {"total":"3","rows":[]}
THE PROBLEM IS: the rows are empty but it counts how many rows are in the db meaning that the connection is good but the query for the row is not working any suggestions?
You are mysql_real_escape_stringing your parameters before establishing a connection to the database. mysql_real_escape_string needs an existing connection to the database to do its job. If there is none, it'll try to establish a connection by itself, which most likely fails, which means your parameters are null.
That should've been easy to figure out if you'd've enabled error reporting or would have debugged your app by simply var_dumping various variables here and there.