second mysqli_query fails - php

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.

Related

PHP While Loops In While Loops not working

Hi I have had a long search for this but have found no fix.
My code is as follows:
$link = mysqli_connect("localhost",".........","...........",".........") or die("Error " . mysqli_error($link));
$ctime = time();
$check = "SELECT * FROM thread WHERE forumid='48' AND visible='1' ORDER BY lastpost DESC LIMIT 1" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$rc = mysqli_query($link, $check);
while($rows = $rc->fetch_assoc()){
$pid = $rows['firstpostid'];
$query = "SELECT * FROM dropouts WHERE date <= $ctime" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$result = mysqli_query($link, $query);
$row_cnt = $result->num_rows;
while($row = $result->fetch_array())
{
$date = $row['date'];
$user = $row['username'];
$sql = "DELETE FROM dropouts WHERE date = $date" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$done = mysqli_query($link, $sql);
//////////////////////////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
$check1 = "SELECT * FROM post WHERE postid='$pid'" or die("Error in the consult.." . mysqli_error($link));
//execute the query.
$rc1 = mysqli_query($link, $check1);
while($row1 = $rc1->fetch_array())
{
$text = $row1['pagetext'];
echo str_replace($user, "", $text);
}
}
}
The problem is that when I run it like that I get no out put.
If I run it so that the while loops are not in eachother I get output but the script only does it for one row post/row.
Does anyone know how to fix this?
I read that it should work but this just isn't working...
Thanks
Have you tried echoing it. It can be that the query returns 0 or empty!
As a beginner in php, you may stumble into these kinds of issues. The best way to understand the problem would be to ECHO & EXIT. Check each step by doing this and you can better understand the problem.
In the problem above, instead of writing the entire code, first of all try checking the small portion of codes and remember:
The best compiler/interpreter lies between you two ears!!

i want to execute a saved query in the database

I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.

PHP, resource id# instead of actual string

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.

Adding either DISTINCT or GROUP BY to my mysql_query is causing no values to be returned

I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.

How to use multiple database using php?

I have read multiple question in the internet including this stackoverflow question but none of them working for me. Here is my code:
<?php
$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
mysql_select_db("asteriskcdrdb",$conn1);
mysql_select_db("pj8v2",$conn2);
$query = "SELECT * FROM cdr";
$result = mysql_query($query,$conn1);
var_dump($result);
$query2 = "SELECT * FROM tb_did_avalaible";
$result2 = mysql_query($query2,$conn2);
var_dump($result2);
?>
When i var_dump the result, it return false. What is the problem here? Thank you.
You dont need two connections, if both databases are located on the same mysql-server and you access them both as unique user.
You also don't need to select a DB.
Just use the database-name as prefix when specifying the tables:
<?php
mysql_connect("localhost","root","pass") or die(mysql_error());
$query = "SELECT * FROM asteriskcdrdb.cdr";
$result = mysql_query($query)or die(mysql_error());
var_dump($result);
$query2 = "SELECT * FROM pj8v2.tb_did_avalaible";
$result2 = mysql_query($query2)or die(mysql_error());
var_dump($result2);
?>
The real problem in your code is: there can only be one active DB, it should work this way:
<?php
$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd",true) or die(mysql_error());
mysql_select_db("asteriskcdrdb",$conn1);
$query = "SELECT * FROM cdr";
$result = mysql_query($query,$conn1);
var_dump($result);
mysql_select_db("pj8v2",$conn2);
$query2 = "SELECT * FROM tb_did_avalaible";
$result2 = mysql_query($query2,$conn2);
var_dump($result2);
?>
Altough there's no need for 2 connections, you can select both DB's using the same connection.
Sorry i just figure out the problem. If using same connection parameter, must add true in the connect parameter
$conn1 = mysql_connect("localhost","root","passw0rd") or die(mysql_error());
$conn2 = mysql_connect("localhost","root","passw0rd",true) or die(mysql_error());
Don't use mysql connector, use mysqli. It is more secure compared to mysql.
the code would be.
$conn1 = new mysqli("localhost","user","password","db1");
$conn2 = new mysqli("localhost","user","password","db2");
$query1 = "select * from table1";
$query2 = "select * from table2";
echo $query1 . "<br />";
echo $query2 . "<br />";
$rs1 = $conn1->query($query1);
$rs2 = $conn2->query($query1);
Also check if the the query is correct. Most of the times the error is in the query and not the syntax.

Categories