Syntax error, unexpected '$query' (T_VARIABLE) - mysql

$koneksi = mysqli_connect($host_name, $username, $password, $database);
$query = mysqli_query($koneksi, "SELECT * FROM pembeli");
$hasil = mysqli_query($query);
while ( $buyer = mysqli_fetch_assoc($hasil)){
echo $buyer ['Nama'];
echo $buyer ['Barang'];
echo $buyer ['Retribusi'];
}
I have that line of code, its produce syntax error unexpected '$query'(T_VARIABLE). Whats wrong ?

In mysqli no need to write :- mysql_select_db($database);
because fourth param in is database name
example :- mysqli_connect($localhost, $username, $password, $database);
Update your code as shown below
$database = "jaka_crud_ci";
$koneksi = mysqli_connect($host_name, $username, $password, $database);
$query = mysqli_query($koneksi, "SELECT * FROM pembeli");
while ( $buyer = mysqli_fetch_assoc($query)){
echo $buyer['Nama'];
echo $buyer['Barang'];
echo $buyer['Retribusi'];
}

Related

errors on mysql says check the manual

I've been receiving this error.
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 'schoolPass = '300570'' at line 1.
please help here is my code for login.php.
<?php
session_start();
require_once '../cn.php';
require_once '../functions.php';
if (isset($_POST['email']) && ($_POST['password'])){
$email = sanitizeString($_POST['email']);
$pass = sanitizeString($_POST['password']);
$query = "SELECT schoolEmail,schoolPass FROM schools WHERE schoolEmail =
'$email' schoolPass = '$pass'";
$result = mysqli_query ($conn, $query) or die (mysqli_error($conn));
$count = mysqli_num_rows ($result);
if ($count == 1) {
echo "pwede na";
} else {
$err = "Invalid Log in Credentials";
};
if (isset($_SESSION['email'])){
$email = $_SESSION['email'];
echo ("hello.$email.");
};
} else {
echo "email/ password not set";
};
$conn->close();
?>
Replace your code line:
$query = "SELECT schoolEmail,schoolPass FROM schools WHERE schoolEmail =
'$email' schoolPass = '$pass'";
BY
$query = "SELECT schoolEmail,schoolPass FROM schools WHERE schoolEmail =
'$email' AND schoolPass = '$pass'";
$query = "
SELECT schoolEmail
, schoolPass
FROM schools
WHERE schoolEmail = '$email'
AND schoolPass = '$pass'
";
In between your two conditions on WHERE, it should be separated by an AND or an OR or a NOT.

Looking for a cleaner way to run a query that has to check for multiple "AND" conditions

I'm running a query against a database and have to check for multiple conditions to be true. The code I have pulls the data I want, but if I had to check many more columns, it could get out of control very quickly. I don't want a query that where I have to write out a dozen or so "AND" conditions. I'm learning some MySQL as I go and any help would be appreciated.
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Set up and run my Query
$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate FROM Projects
WHERE FinalReviewDate IS NOT NULL
AND DateDelivered IS NULL
AND DateAccepted IS NULL
ORDER BY DateAccepted DESC";
$result = $conn->query($sql);
//Display results
if ($result->num_rows > 0) {
echo "<table><tr><th>Client</th><th>Project</th><th>Point of Contact</th><th>Date Project Received</th><th>Final Review Date</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row ["Project"]. "</td><td> " . $row["LastName"]. "</td><td> " . $row ["DateReceived"]. "</td><td> " . $row["FinalReviewDate"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
You can use an array for your and conditions. But in general you have to be careful if you are going to have prepared statements and bind values. Also, you can create your WHERE clause dynamically in a similar way like the following:
EDIT:
$where = array(
array(
'column'=>'FinalReviewDate',
'operator'=>'AND',
'condition'=>'IS NOT NULL',
'value'=>'',
),
array(
'column'=>'DateDelivered',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'DateAccepted',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'other_column',
'operator'=>'OR',
'condition'=>'>=',
'value'=>5,
),
);
$temp = array();
foreach($where as $key => $value) {
if ($value['value'] == '') {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'];
} else {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'].' '.$value['value'];
}
}
$where_sql = '1 = 1 '.implode(' ', $temp);
echo $where_sql;
Result:
1 = 1 AND FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL OR other_column >= 5
OLD ANSWER
$ands = array(
array(
'column'=>'FinalReviewDate',
'condition'=>'IS NOT NULL'
),
array(
'column'=>'DateDelivered',
'condition'=>'IS NULL'
),
array(
'column'=>'DateAccepted',
'condition'=>'IS NULL'
),
);
$temp = array();
foreach($ands as $key => $value) {
$temp[] = $value['column'].' '.$value['condition'];
}
$and_sql = implode(' AND ', $temp);
echo $and_sql;
Result:
FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL

MySQL Syntax Error with wpdb query/prepare

I'm simply trying to run a query using wpdb query and prepare statements.
On my page it returns:
[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 'myQuery' at line 1]
PHP Code:
<?php
$dirName1 = 'C:/wamp/www/c2c/wp-content/themes/flawless-v1-01';
$dirName2 = 'C:/wamp/www/c2c';
require_once($dirName1.'/config/setup.php');
require_once($dirName2.'/wp-config.php');
require_once($dirName2.'/wp-load.php');
$wpdb->show_errors();
$tableName = $wpdb->prefix . "user_orders";
$user = wp_get_current_user();
$userId = $user->ID;
$userName = $user->user_login;
// echo $tableName . ': ' . $userId . ': '. $userName;
// echo var_dump($tableName);
// echo var_dump($userId);
// echo var_dump($userName);
// These echo the correct formats for the prepare statement below
$myQuery = $wpdb->query(
$wpdb->prepare("
SELECT *
FROM $tableName
WHERE `user_id` = %d
AND `user_name` = %s",
$tableName,
$userId,
$userName)
);
$results = $wpdb->get_results(myQuery, ARRAY_A);
?>
You're missing the dollar sign before your variable name:
$results = $wpdb->get_results(myQuery, ARRAY_A);
should be
$results = $wpdb->get_results($myQuery, ARRAY_A);

Prepared statements in mysqli not working

Can someone explain to me why this isn't working. Trying to convert to prepared statements as per the advice of everybody but get stuck right at the beginning...the connection is fine and it returns no message, but there is no entry into my table (called nametable)
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")");
}
$query = "INSERT INTO nametable (fname, lname) values (?,?)";
$stmt = mysqli_prepare($con, $query);
$firstName = "simon";
$lastName = "morris";
mysqli_stmt_bind_param($stmt,"ss",$firstname, $lastname);
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", $stmt->error);
$stmt->close();
?>
I added the last 2 lines and the error that comes back is
Error: .
This works just fine but the prepared statements do not....anyone know why?
$sql="INSERT INTO nametable (fname, lname)
VALUES ('$firstName', '$lastName')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
try this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$firstName = "simon";
$lastName = "morris";
if ($stmtb = $mysqli->prepare("INSERT INTO nametable (fname, lname) values (?,?)")) {
$stmtb->bind_param('ss',$firstName, $lastName);
$stmtb->execute();
}else {printf("Prepared Statement Error: %s\n", $mysqli->error);}

How would I add to table values then show the total on my website

I want to add two table totals together, and then place it on my website here's the code I tried.
<?php
$host = "localhost";
$username = "runerebe_online";
$password = "***";
$db_name = "runerebe_online";
mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name") or die(mysql_error());
$host = "localhost";
$username = "runerebe_online2";
$password = "***";
$db_name = "runerebe_online2";
mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name") or die(mysql_error());
$total = "SELECT (online + online2)";
$rs = mysql_query($total);
while($row = mysql_fetch_array($rs)) {
echo $row['total'];
}
mysql_close();
?>
This is the error printing when I use this
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/runerebe/public_html/home/index.php on line 63
This is line 63, and what it contains
63: while($row = mysql_fetch_array($rs)) {
64: echo $row['total'];
65: }
Your query is invalid. That is why mysql_query() fails and returns FALSE instead of a resource that is needed for mysql_fetch_array() to succeed.
If you need to read two values from two different databases and if a user has permissions granted to do select on both databases and is currently connected to the database online you can do that with a statement like this
SELECT
(SELECT SUM(o2.columnname) FROM runerebe_online2.tablename o2) +
(SELECT SUM(columnname) FROM tablename) TOTAL
Otherwise you need to retrieve two values separately in php like this
//Connect and get a value from db 'runerebe_online'
...
$db_name = "runerebe_online";
$link1 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db($db_name, $link1) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link1);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal1 = $row['subtotal'];
mysql_free_result($result);
mysql_close($link1);
//Connect and get a value from db 'runerebe_online2'
...
$db_name = "runerebe_online2";
$link2 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name", $link2) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link2);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal2 = $row['subtotal']
mysql_free_result($result);
mysql_close($link1);
$total = $subtotal1 + $subtotal2;
echo $total;
...