PHP, resource id# instead of actual string - php

I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zer‌​o."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE

You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.

Related

I am writing a madlib in php, saving it to a db using mysql, then trying to pull out each new story in descending order

I am not sure how to get the story out of the db, I am getting this error:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
string given in /home/ubuntu/workspace/projects/project_1/madlib.php
on line 33 Call Stack: 0.0009 248160 1. {main}()
/home/ubuntu/workspace/projects/project_1/madlib.php:0 0.0058 257240
2. mysqli_fetch_array() /home/ubuntu/workspace/projects/project_1/madlib.php:33
<?php
//connecting to the db
$dbc = mysqli_connect('localhost', 'root', '', 'project1')
or die('Error connecting to MySQL server.');
//creating variables
$noun = $_POST['noun'];
$verb = $_POST['verb'];
$adjective = $_POST['adjective'];
$body_part = $_POST['bodypart'];
$food_item = $_POST['fooditem'];
$full_story = "Here are some things to do at recess."
"Start a game of touch $body_part-ball."
"Put a $noun in someones lunch."
"Start a $food_item fight in the school $adjective room."
"Choose sides and have a $verb ball tournament.";
//inserting form info into db
$query = "INSERT INTO my_game (noun, verb, adjective, body_part, food_item) " .
"VALUES ('$noun', '$verb', '$adjective', '$body_part', '$food_item')";
//get query result from db
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
if(empty($noun) || empty($verb) || empty($adjective) || empty($body_part) || empty($food_item)) {
echo "You have not filled in all of the fields.Please go back and try again.";
}
$query2 = "SELECT * FROM my_game WHERE id ORDER BY desc";
//while loop grabs name from array
while($row = mysqli_fetch_array($query2)) {
$noun = $row['noun'];
$verb = $row['verb'];
$adjective = $row['adjective'];
$body_part = $row['body_part'];
$food_item = $row['food_item'];
$full_story = "Here are some things to do at recess."
"Start a game of touch $body_part-ball."
"Put a $noun in someones lunch."
"Start a $food_item fight in the school $adjective room."
"Choose sides and have a $verb ball tournament.";
//outputs story
echo $full_story;
}
//close connection
mysqli_close($dbc);
?>
You are not executing the query before trying to fetch. The query is just a string in $query2.
You need to execute the query by calling mysqli->query
Since you already did this above it looks like you just missed it all together on the second query by accident. ( I've done this before).
After this line
$query2 = "SELECT * FROM my_game WHERE id ORDER BY desc";
You can do something like
//get query result from db
$result2 = mysqli_query($dbc, $query2)
or die('Error querying database.');
and change this accordingly
while($row = mysqli_fetch_array($result2)) {

Display Bids from database in order

Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}

mySQL statement not running in PHP variable declaration

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

second mysqli_query fails

the first query is fine but the second one wont work it just dies.
I plug the $city variable into the second one and echo it back and it shows the correct
value but its the the actual:
$row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
that fails... please help!
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or WriteMessage('Error', 'Could not connect to the Database...');
//get user city...
$userID = $_SESSION['userID'];
$queryUserCity = "SELECT * from user where userID = $userID";
$GetResult = mysqli_query($dbc, $queryUserCity)
or die('Error while querying the Database');
$getRow = mysqli_fetch_array($GetResult);
$city = $getRow['city'];
$state = $getRow['state'];
$username = $getRow['username'];
echo 'username='.$username.' ';
echo 'city='.$city;
echo 'state = ' .$state;
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
//fails right here...
/*-->*/ $row = mysqli_query($dbc, $query)
or die('Error while querying the Database');
echo $query;
exit();
while($row = mysqli_fetch_array($data))
{
You are trying to find a string without single quote. You use integer without single quote but in case of string you have to use single quote with your string.
change
$query = "SELECT * FROM adds where city = $city ORDER BY addDate ASC";
to
$query = "SELECT * FROM adds where city = '$city' ORDER BY addDate ASC";
and to find out exact error try to use the below code.
if (!mysqli_query($dbc, $query)){
echo("Error description: " . mysqli_error($dbc));
}
If the city is a textual type (and it probably is), you'll need:
... where city = '$city' ...
But, in fact, you shouldn't really be doing it that way anyway, since it opens you up to the possibility of SQL injection attacks if someone can enter arbitrary text for their city.
You should start looking into parameterised queries since they can protect you from such attacks. See Exploits of a Mom and the invaluable explain-xkcd entry.

Fastest way to find, fetch and replace part of the string in database

I have a set of records in database table and one of the columns has string value. Something like HeyHelloWorld1 or HeyGoodDayWorld2 or HeyHowdyWorld32. I need to change them all to GoodEveningWorld (and whatever comes at the end of the string). I'm trying to run script but it takes too long and I was wondering if anyone knows of a fastest way to implement this
The script:
$con=mysqli_connect("localhost","user","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$str_to_look_for = 'Hey';
$new_str = 'GoodEvening';
$result = mysqli_query($con,"SELECT * FROM table1 WHERE item LIKE '%$str%'");
if(!$result) echo "No records found?";
else
{
echo " Found ".mysqli_num_rows($result)." rows<br/>... Executing script...";
while($row = mysqli_fetch_array($result))
{
$val = strstr($row['item'], '/World');
$new_val = $new_str.$val;
$id = $row['ID'];
insert($new_val, $id, $con);
}
echo " DONE!";
}
function insert($x, $id, $con)
{
$result = mysqli_query($con,"UPDATE table1 SET item = '$x' WHERE ID = '$id'");
if (!$result) echo "missed..<br/>";
}
Check out the MySQL String functions and consider replacing it directly in the database.
UPDATE table1
SET item =
CONCAT(
'GoodEvening',
SUBSTRING( item, INSTR( item, 'World') )
)
This would work for anything followed by World, rather than just HelloWorld or HayWorld.

Categories