So previously my queries were working fine. I usually use mysql but have recently changed to a pre-configured vps through godaddy. Last night I was trying to connect to my server via PDO, which is showing the connection is being made.
Next I was trying to select the data from a table using:
global $conn;
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetch();
All this shows on my website is Connection Successful, Array
It doesn't show any array information or anything, just the word "Array". The table has information in it, so it should be displaying the results. Any idea of what I am doing wrong?
You get Array because you are echoing an array. Fetch returns an array,
PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set
Since you are querying a full table you probably want all the results so you should loop the fetch and return that array.
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
while($row = $stm->fetch()) {
$returned_array[] = $row['name'];
}
return $returned_array;
Then iterate over this where ever you are using it for all the supplier names.
foreach(function_call_for_names() as $name) {
echo $name;
}
Alternately, you could use the PDO fetchAll function,
$sql = "SELECT name FROM suppliers";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll();
then
foreach(function_call_for_names() as $row) {
echo $row['name'];
}
Related
$sql = "select classname,id,name,value,description from tablename";
$query = $this->conn->prepare($sql);
$query->execute();
$result = $query->fetch(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE);
var_dump($result);
Result shows stdClassObject
Expected is the classname object (of the particular row)
Basically, am trying to loop through the result, figure out which class the row belongs to and access their getter functions. Same is achieved if I use the following, but not the solution that works for me.
$sql = "select classname,id,name,value,description from tablename";
$query = $this->conn->prepare($sql);
$query->execute();
$result = $query->fetch(PDO::FETCH_CLASS, 'MyClass');
var_dump($result);
Now, I can loop through the result and access $result->getId() or $result->getName() etc. How I can achieve this through PDO::FETCH_CLASSTYPE as the classname is dynamically decided by the row in the result set.
I want an if-statement that only runs, when there are no rows in the table or if existing rows dont match a specific parameter from my input. I tried this way:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql);
if(!$result)
{ ... }
From my thinking this should execute the if-statement on the first time I want to add something to the database and if the $currentURL does not exist in existing data. But this does not seem to work the way I think it does. How would you do this? Maybe I'm handling the $result wrong, because if I test the sql-query inside phpmyadmin this shows the right result (no rows).
The correct way to do this would be to use prepared statement and fetch the results into an array. You can fetch all rows into an array using fetch_all()
$stmt = $conn->prepare("SELECT * FROM images WHERE imageURL = ?");
$stmt->bind_param('s', $post["media_url"]);
$stmt->execute();
// Get result and then fetch all rows from the result object
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Then check if you have any rows at all using a simple if statement
// Negate it using ! to check if the array is empty
if (!$result) {
// no results found
}
I guess, that $conn is a PDO connection? In that case, the method $conn->query() returns an object of type PDOStatement. See https://www.php.net/manual/de/class.pdostatement.php
The method does NOT return the result set.
Instead you can use the PDOStatement object, to fetch the results:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetchAll();
if(empty($result))
{ ... }
In case you are using mysqli, the object returned by query() is this: https://www.php.net/manual/en/class.mysqli-result.php
So the code would be:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
if(empty($result))
{ ... }
Please also note: Your code is highly insecure! You should use prepared statements to prevent sql-injection:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = :currentUrl";
$stmt = $conn->prepare($sql);
$stmt->execute(['currentUrl' => $currentURL]);
$result = $stmt->fetchAll();
if(empty($result))
{ ... }
sanitize input against sql injection (or better - use prepared statements and param binding)
$sql = "SELECT * FROM images WHERE imageURL = '".$conn->real_escape_string($currentURL)."'";
mysqli query returns true on success (even empty dataset is success), use num_rows instead:
if ( $result->num_rows === 0 ) { ... }
I am new when it comes to php, SQL and still learning, I am trying to get the last 4 string value of my column where the value is a telephone numbers: (7258787)
I am trying to display the last 4 string even the search query is full 7 string (8787) base on what i have read SUBSTRING(column_name, -4) will result the last 4 strings from the right.
my codes returns undefined, can you enlighten me with this?
if (isset($_GET['telephone'])) {
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT telephone, SUBSTRING(telephone,-4)FROM employee';
Using this:
$sql = 'SELECT * FROM employee WHERE telephone like ?';
will result the correct value of 7258787 but it will result the whole string(telephone numbers) that i type on a search box
Thank you in advance
This is the whole code:
This is not the answer but the whole script, (credits to Israel Barragan)
In my database I have employee as table and the columns are 'ID', 'NAME', 'TELEPHONE', and 'EMAIL'
<?php
header('Content-Type: application/json');
require_once 'Connectiondb.php';
$conn = dbConnect();
$OK = true; // We use this to verify the status of the update.
if (isset($_GET['telephone'])) {
// Create the query
$data = "%".$_GET['telephone']."%";
$sql = 'SELECT * FROM employee WHERE telephone like ?';
// we have to tell the PDO that we are going to send values to the query
$stmt = $conn->prepare($sql);
// Now we execute the query passing an array toe execute();
$results = $stmt->execute(array($data));
// Extract the values from $result
$rows = $stmt->fetchAll();
$error = $stmt->errorInfo();
//echo $error[2];
}
// If there are no records.
if(empty($rows)) {
echo json_encode( array('error'=>'There were not records','0'=> 'There were not records'));
}
else {
echo json_encode($rows);
}
?>
sorry I am new to stackoverflow,
You can bind the result in your query, and then get the last 4 digits from that to display.
For instance, you can do this
(not you aren't binding your parameters. You need to do something like this)
$stmt->bind_param("s", $data);
and then execute it like this:
$stmt->execute();
In your query instead of using select *, name the specific keys and then you can bind the result like this (assuming all you need is the phone number:
$stmt->bind_result($telephone);
then get the result like so:
$stmt->fetch();
then you can just get a substring off of $telephone like so (in php it is substr())
echo substr($telephone,-4);
(oh yeah and don't forget to close your object with
$stmt->close();
after you are done)
Edit:
Here's your query put together to get the substring
$data = "%".$_GET['telephone']."%";
$stmt = $conn->prepare("SELECT telephone FROM employee WHERE telephone like ?");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->bind_result($telephone);
$stmt->fetch();
echo substr($telephone,-4);
$stmt->close();
Hello I have a prepared statement and I need to count the number of results I get. In order to do this I use store_result and num_rows
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
This code manages to get me the number of rows. The problem is that if I do this I cannot use fetch() on $rsActivation. If I use fetch and not use store_result I cannot get the number of rows.
How can I accomplish both things?
Thanks
SOLVED:
Turns out my problem was I was trying to fetch the results as an associative array. Instead I used bind_result to assign values to variables. Then I was able to use store_result and num_rows to get the count and after that I used fetch() together with the variables I assigned in bind_result.
$query = 'SELECT userId, promo, email FROM users WHERE active = ?';
$rsActivation = $db->prepare($query);
$rsActivation->bind_param('s', $actv);
$rsActivation->execute();
$rsActivation->bind_result($userId, $promo, $email);
$rsActivation->store_result();
$totalRows = $rsActivation->num_rows;
while($rsActivation->fetch()){
echo "<p>". $userId ."</p>";
...
}
You can try using
...
$rsActivation->execute();
$results = $rsActivation->get_results();
$totalRows = $results->num_rows;
and you should be able to fetch using something like
$results->fetch_assoc(), $results->fetch_row(), etc.
Here's the doc for it: http://php.net/manual/en/class.mysqli-result.php
Below is the code, I have, it is written in mysql. My goal is to convert this to PDO.
$query = "SELECT name, age FROM table WHERE condition=$condtion";
$mysql_query = mysql_query($query);
echo $name = mysql_result($mysql_query, 0, 'name');
echo $age = mysql_result($mysql_query, 0, 'age');
I have tried doing the following code below, but it is giving me an empty result.
$query = $PDO -> prepare("SELECT name, age FROM table");
$query -> execute();
echo $name = $query->fetch(PDO::FETCH_ASSOC)['name'];
echo $age = $query->fetch(PDO::FETCH_ASSOC)['age'];
Try:
$query = $PDO->prepare("SELECT name, age FROM table WHERE condition = :param");
$query->bindParam(':param', $param); // define this somewhere
$query->execute();
$result = $query->fetch();
echo $name = $result['name'];
echo $age = $result['age'];
From PHP.net, fetch works as follows:
Fetches a row from a result set associated with a PDOStatement object. The fetch_style parameter determines how PDO returns the row.
When you execute a prepared statement, you need to perform a fetch or a fetchAll to pull the data. fetch gets you the first row, and in your case with a condition = X, I am guessing you only want one row.
Updated with links for reference:
execute: http://php.net/manual/en/pdostatement.execute.php
fetch: http://php.net/manual/en/pdostatement.fetch.php